ファイル操作 - Python3

ファイル操作

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)

ファイルを読み込む

  • test.py
  • test.txt

test.py

with open('./test.txt', encoding="utf8") as f:
  file = f.read()

print(file)

test.txt

apple
orange
banana

open()関数の mode引数

引数の値 内容
w 書き込みモード。既存のファイルの場合、ファイルの内容はすべて上書きされます
r 読み込みモード(デフォルト
a 書き込みモード(追記)。既存ファイルの場合、末尾に追記
b バイナリモード
t テキストモード

f = open("./test.txt", mode="w", encoding="utf-8")
f.write("Hello, Python")
f.close()

ファイルの途中に書き込む

readlines() は、ファイルの内容をリストで取得します。

  • test.py
  • test.txt

test.py

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)

test.txt

1
2
3
4
5