12 : 言語処理100本ノックでPythonのお勉強

第二章 : 12 1列目をcol1.txtに、2列目をcol2.txtに保存

各行の1列目だけを抜き出したものをcol1.txtに,2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ.確認にはcutコマンドを用いよ

コードはこんな感じ。

f = 'hightemp.txt'
f1 = 'col1.txt'
f2 = 'col2.txt'

with open(f) as file, open(f1, 'w') as file1, open(f2, 'w') as file2:
    for line in file:
        cols = line.split('\t')
        file1.write(cols[0] + '\n')
        file2.write(cols[1] + '\n')

open()関数の第2引数'w'がないとファイルが無い場合、新規にファイルを作成してくれません。プログラムの中で新規ファイルを作成する場合、忘れないように注意せねば。

Unixコマンドで行なう場合はcutを使います。

# 1列目をカットして新規ファイルに。
$ cut -f 1 hightemp.txt > col1.txt
# 2列目をカットして新規ファイルに。
$ cut -f 2 hightemp.txt > col2.txt

Qiitaのこちらの記事を参考にしています。