' P '

whatever I will forget

Python ファイル入出力

データサイエンスとかやるなら、これ必須やと思います。
整形するときにcsvとか開くやん、、
open/closeとメソッドはありますが、基本with openしておけば間違いないです。
上記だと、ブロックから抜けたら勝手にcloseしてくれるからです。

#ファイル書き込み、すでにファイルがある場合は上書き
with open('tmp.csv', 'w') as f:
    f.write('hello world\n')
    f.write('hello world2\n')
    f.write('hello world3\n')

#ファイルオープン
#ファイルの中身をすべて取得
with open('tmp.csv', 'r') as f2:
    file_str = f2.read()
    print(file_str)

    #hello world
    #hello world2
    #hello world3

#ファイルオープン。
#ファイルの内容をfor文で一行ずつ表示。
with open('tmp.csv', 'r') as f3:
    for str in f3:
        print(str)

        #hello world
        #
        #hello world2
        #
        #hello world3
        #

#ファイルオープン。
#ファイルにある値を一行だけ取得して表示。
with open('tmp.csv', 'r') as f4:
    str = f4.readline()
    print(str)

    #hello world

一応、open時のモードを書いておきます。

  • r (read)
  • w (write,既存ファイルがある場合は上書き)
  • x (排他モード、既存ファイルがある場合はエラー)
  • a (追加モード、ファイルがある場合は末尾に追記)   
  • b (バイナリモード)
  • t (テキストモード)