今さらPython

読み込み

f = open(filename)
d = f.read()  # ファイル終端まで全て読んだデータを返す
f.close()

読み込み(2)明示的closeをしない

明示的にクローズしなくても、これで閉じられる。

with open(path) as f:
   s = f.read()

読み込み(3)リストで読み込み

行ごとに分割したリストとして読み込む。

with open(path) as f:
   l = f.readlines()

読み込み(4)一行ずつ取得

with open(path) as f:
   for s_line in f:
       print(s_line)

書き出し

with open(filename, mode='w') as f:
    f.write("データ")

上書き禁止で新規作成

with open(path_w, mode='x') as f:
    f.write(s)

トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2020-03-09 (月) 18:02:01