lispとrubyとpythonと その8 ファイルIO(python)

PytyonでのIO。
with ... as を綺麗にかけるととるか不格好ととるか。。。

#確保と開放はwith ... as で。

with open("test.txt","w+") as f:
    f.write("hello world\n")

with open("test.txt","r") as f:
    for l in f:
        print(l)
#->hello world

#バイナリファイル読み書き
with open("test.dat","wb+") as f:
    f.write([0,1,2])

with open("test.dat","rb") as f:
    for l in f:
        print(l)
#->b'\x00\x01\x02'