TIL

Today I Learned. 知ったこと、学んだことを書いていく

ファイルを読み込み(と書き込み)

ファイルの読み書きにはopen()を使う。

第一引数には対象のファイルのパス、第二引数にはモードを指定する。

第二引数について

引数 モード
r 読み取り
w 書き込み
a 追加書き込み


読み込みを行う場合

>>> with open('/Users/tamago324/test.txt', r) as f:
...   read_data = f.readline()
...
>>> read_data
'hello!\n'

withを使えば、クローズ処理が必要なくなる。

読み込むメソッド

  • read(): すべて読み込む
  • readline(): 1行読み込む
  • readlines(): すべて読み込み、リストを返す


書き込みについて少しだけ(2017/10/14)

書き込みのメソッドであるwriteline()はリストを書き込むメソッドとなっているが、要素ごとに改行がされない。そのため、要素を\nで結合してあげる必要がある。

改行なし

words = ['hello', 'world', '!!!']
with open('test.txt', 'w') as f:
    f.writeline(words)

test.txt

helloworld!!!

改行あり

words = ['hello', 'world', '!!!']
with open('test.txt', 'w') as f:
    f.writeline('\n'.join(words))

test.txt

hello
world
!!!

リストの要素を書き込むときには改行で結合する!


参考文献