kade

技術系の記事を書いていきます。

Python2.7: ファイルの読み書き

読み

path = "./hoge.txt"
file = open(path)
firstLine = file.readline() # 1行ずつ読み
secondLine = file.readline() # 次の行
file.close()
file = open(path)
desc = file.read() # 全文読み
file.close()
file = open(path)
for line in file
  print line # 行毎に何か処理したい場合など 
file.close()

書き

path = "./hoge.txt"
file = open(path, "w")
file.write("変数でstrを突っ込んでも良いし直接書いても良いし。")
file.close()

初めてのPython 第3版

初めてのPython 第3版