ファイル入出力の基礎
Pythonでファイルを扱う際は、open()関数を利用します。基本的な構文は以下の通りです。
ファイルオブジェクト = open(パス, モード)アクセスモード一覧
| モード | 動作 |
|---|---|
r | 読み取り専用。ファイル先頭にポインタを設定(デフォルト) |
w | 書き込み専用。既存ファイルは上書き、存在しない場合は新規作成 |
a | 追記モード。既存ファイルの末尾に追加、存在しない場合は新規作成 |
rb | バイナリ読み取り |
wb | バイナリ書き込み |
ab | バイナリ追記 |
r+ | 読み書き両方。ファイル先頭から |
w+ | 読み書き両方。既存ファイルは上書き |
a+ | 読み書き両方。追記ベース |
rb+ | バイナリ読み書き |
wb+ | バイナリ読み書き(上書き) |
ab+ | バイナリ読み書き(追記) |
ファイル操作の流れ
ファイル処理は「オープン → 読み書き → クローズ」の3ステップで行います。リソース解放のため、使用後は必ずクローズが必要です。
読み取りの例
# sample.txt を読み取りモードで開く
handler = open('sample.txt', 'r')
text = handler.read()
print(text)
handler.close()書き込みの例
# 新規ファイルに複数行を書き込む
output = open('output.txt', 'w')
output.write("""first line
second line
third line""")
output.close()
# 空ファイルの作成
empty = open('empty.txt', 'w')
empty.close()
# 既存ファイルへの追記
appender = open('output.txt', 'a')
appender.write("\nappended text")
appender.close()主要なメソッド
readlines():全行をリストで取得
handler = open('output.txt', 'r')
rows = handler.readlines()
print(rows)
handler.close()
# 出力例: ['first line\n', 'second line\n', 'third line\n', 'appended text']readline():1行ずつ取得
handler = open('output.txt', 'r')
first_row = handler.readline()
print(first_row) # 先頭行のみ取得
handler.close()tell():現在のポジションを確認
handler = open('/etc/passwd', 'r')
print(handler.tell()) # 0(ファイル先頭)
content = handler.read()
print(handler.tell()) # ファイル末尾のバイト位置
handler.close()seek():ポジションを移動
seek(オフセット, 基準点)でファイルポインタを移動します。基準点は0(先頭)、1(現在位置)、2(末尾)を指定します。
handler = open('/etc/passwd', 'r')
handler.read() # 全体を読み込む
print(handler.tell()) # 末尾位置
handler.seek(5, 0) # 先頭から5バイト目へ
print(handler.tell()) # 5
print(handler.read()) # 5バイト目以降を読み込む
handler.close()read():指定サイズを読み込む
handler = open('output.txt', 'r')
all_content = handler.read() # 全体を読み込む
handler.seek(0)
partial = handler.read(10) # 先頭から10文字を読み込む
handler.close()文字エンコーディングの指定
日本語を含むテキストをう場合は、encodingパラメータでUTF-8を明示することが推奨されます。
# 書き込み時にエンコーディングを指定
writer = open('japanese.txt', 'w', encoding='utf-8')
writer.write('東京都港区\n')
writer.close()
# 読み込み時も同じエンコーディングを指定
reader = open('japanese.txt', 'r', encoding='utf-8')
print(reader.read())
reader.close()コンテキストマネージャ(with文)
with文を使用すると、ブロック終了時に自動的にclose()が呼ばれます。複数ファイルの同時オープンも可能です。
# 単一ファイル
with open('data.txt', 'r') as src:
print(src.read())
# 複数ファイル(ファイルコピーの例)
with open('/etc/passwd', 'r') as src, \
open('/tmp/passwd_copy', 'w+') as dst:
dst.write(src.read())
dst.seek(0)
print(dst.read())ファイルバックアップの実装
with open('original.txt', 'r') as original, \
open('original_backup.txt', 'w') as backup:
backup.write(original.read())osモジュールによるファイルシステム操作
ファイル名変更、削除、ディレクトリ操作などはosモジュールを利用します。
ファイル名の変更
import os
os.rename('old_name.txt', 'new_name.txt')ファイルの削除
import os
os.remove('target.txt')ディレクトリの作成
import os
os.mkdir('new_directory')カレントディレクトリの取得
import os
print(os.getcwd())空ディレクトリの削除
import os
os.rmdir('empty_directory')ディレクトリ内容の一覧取得
import os
print(os.listdir('.'))作業ディレクトリの変更
import os
os.chdir('/tmp/work')
print(os.getcwd())バッチ処理の例
複数ファイルの一括生成
import os
os.mkdir('generated_files')
os.chdir('generated_files')
for idx in range(1, 11):
name = f'document_{idx:02d}.txt'
with open(name, 'w') as f:
pass # 空ファイルを作成
print(os.listdir('.'))ファイル名の一括変更
import os
os.chdir('generated_files')
for old_name in os.listdir('.'):
if old_name.endswith('.txt'):
new_name = old_name.replace('.txt', '_processed.txt')
os.rename(old_name, new_name)モード選択のポイント
| 用途 | 推奨モード |
|---|---|
| 既存ファイルを読むのみ | r |
| 新規作成または完全上書き | w |
| 末尾に追加 | a |
| 読み書き両方(上書きあり) | w+ |
| 読み書き両方(追記ベース) | a+ |
| 既存ファイルの読み書き(上書きなし) | r+(ファイル必須) |