ファイル操作
with 構文を使うと、処理の後自動的にファイルをclose() してくれます。
with 構文を使うと、処理の後自動的にファイルをclose() してくれます。
path = './test.txt'
f = open(path, 'w')
f.write('')
f.close()
with 構文を使うと次のように記述できます。
path = './test.txt'
with open(path, 'w') as f:
f.write('')
ファイルを削除するには次のようにします。
import os
path = './test.txt'
os.remove(path)
with open('./test.txt', encoding="utf8") as f:
file = f.read()
print(file)
apple
orange
banana
引数の値 | 内容 |
---|---|
w | 書き込みモード。既存のファイルの場合、ファイルの内容はすべて上書きされます |
r | 読み込みモード(デフォルト |
a | 書き込みモード(追記)。既存ファイルの場合、末尾に追記 |
b | バイナリモード |
t | テキストモード |
f = open("./test.txt", mode="w", encoding="utf-8")
f.write("Hello, Python")
f.close()
readlines() は、ファイルの内容をリストで取得します。
fname = './test.txt'
#ファイルをリストで読み込み
with open(fname) as f:
data = f.readlines()
#3行目に挿入
data.insert(2, 'Hello, Python\n')
#元のファイルに書き込み
with open(fname, mode='w') as f:
f.writelines(data)
1
2
3
4
5