ファイル操作の流れ
大まかな流れは以下のとおり。
- モードを指定してファイルを開く~
open - ファイルへの読み書きを実行
- ファイルを閉じる~
close
具体的には、openでファイルオブジェクトを取得し、読み書きやcloseなどの操作はファイルオブジェクトに対して実行。
基本形
以下のファイルを準備。行末は全て改行コードで終わっている。
|
1 2 3 |
When the dog bytes When the bee stings When I'm feeling sad |
以下のコードは、ファイルを読み込みモードで開き、内容を一つの文字列に一括して読み込んで表示している。
|
1 2 3 4 5 6 7 8 9 10 11 |
# 読み込みモードでファイルをオープン f = open('test.txt', 'r') # ファイルの内容を一括読み込み text = f.read() # ファイルをクローズ f.close() # 読み込んだファイル内容を表示 print(text) |
実行結果は以下のとおり。
|
1 2 3 4 5 6 |
$ python3 filetest.py When the dog bytes When the bee stings When I'm feeling sad $ |
ファイルの各行末に改行コードがあるため、そこで改行されて表示される。さらにprint関数で自動的に改行コードが付加されるため、最後に空白行が入っている。
with文
with文でopenを指定することにより、withブロック終了時に自動的に終了処理(close)が実行される。
|
1 2 3 4 5 6 7 |
# 読み込みモードでファイルを使う with open('test.txt', 'r') as f: # ファイル内容を行に分割してリストに格納 text = f.read() # リストの要素=各行を表示 print(text, end='') |
ファイルからの読み込み
read~一括読み込み
readメソッドはファイルの全内容を一つのテキストとして読み込む。
|
1 2 3 4 5 6 7 8 9 |
# ファイル内容を行に分割してリストに格納 text = f.read() # リストの要素=各行を表示 print(text, end='') # When the dog bytes # When the bee stings # When I'm feeling sad |
readline~一行読み込み
readlineは実行のたびにファイルから1行ずつ読み込み、ポインターを次の行に進める。読み込む内容がない場合には''を返す。
以下はファイルの内容を2行だけ読みだす例。
|
1 2 3 4 5 6 7 8 |
// 1行ずつファイルを読み込みながら表示 line = f.readline() print(line, end='') line = f.readline() print(line, end='') # When the dog bytes # When the bee stings |
以下はファイル内容の全行を1行ずつ取り出す例。
|
1 2 3 4 5 6 7 8 9 |
while True: text = f.read() if text == '': break print(text, end='') # When the dog bytes # When the bee stings # When I'm feeling sad |
readlines~行に分割して読み込み
readlinesはファイルの内容を行に分解し、各行の内容を要素としたリストを返す。
|
1 2 3 4 5 6 7 8 9 10 |
# ファイル内容を行に分割してリストに格納 lines = f.readlines() # リストの要素=各行を表示 for line in lines: print(line, end='') # When the dog bytes # When the bee stings # When I'm feeling sad |
ファイルへの書き込み
ファイルに書き込む場合、オプションに'w'を指定。既にファイルが存在する場合、その内容は無視されて上書きされる。
write文
write文は引数の文字列を単に書き込む。
|
1 2 3 4 5 6 7 8 9 |
# 読み込みモードでファイルをオープン with open('test.txt', 'w') as f: # 1行ずつファイルへ書込み f.write('Raindrops on roses and whiskers on kittens\n') f.write('Bright copper kettles and warm woolen mittens\n') # test.txtの内容 # Raindrops on roses and whiskers on kittens # Bright copper kettles and warm woolen mittens |
print文
print文のfile引数にファイルオブジェクトを指定すると、ファイルに書き込むことができる。この場合、書式設定などを活用することができる。
|
1 2 3 4 5 6 7 |
with open('test2.txt', 'w') as f:# 1行ずつファイルへ書込み print('1 million yen', file=f) print('{:,} yen'.format(1000000), file=f) # test2.txtの内容 # 1 million yen # 1,000,000 yen |
ファイルへの追記
既存のファイルに追記するには'a'オプションを指定。以下の例では、上で作成されたtest.txtに1行追記している。
|
1 2 3 4 5 6 7 8 9 |
# 読み込みモードでファイルをオープン with open('test.txt', 'a') as f:# 1行ずつファイルへ書込み # 1行追記 f.write('Brown paper packages tied up with strings\n') # test.txtの内容 # Raindrops on roses and whiskers on kittens # Bright copper kettles and warm woolen mittens # Brown paper packages tied up with strings |
ファイルが存在しない場合は、'w'と同様にファイルが作成されて新規に書き込みされる。
|
1 2 3 4 5 6 |
$ rm test.txt $ ls filetest.py $ python3 filetest.py $ cat test.txt Brown paper packages tied up with strings |