今回は、Pythonを使ってファイルへの印刷を行う方法をいくつか紹介します。
方法1: Write() を使ってファイルに書き込む
ファイル操作のチュートリアルで学んだ組み込み関数write()を使って、ファイルに直接書き込むことができます。
with open('output.txt', 'a') as f:
f.write('Hi')
f.write('Hello from Python')
f.write('exit')
|
出力 (output.txt が新しく作成されたファイルであると仮定します)
vijay@Python:~# python output_redirection.py
HiHello from Pythonexitroot@ubuntu:~# cat output.txt
HiHello from Pythonexit |
方法2: sys.stdout をファイルへリダイレクトする
通常、print 関数を使用すると、出力はコンソールに表示されます。
しかし、標準出力ストリームはファイルオブジェクトのハンドラでもあるので、標準出力 sys.stdout をルーティングして、代わりに出力先のファイルを指定することができます。
以下のコードは、前回の stdin, stdout, stderr の記事から引用したものです。
これは print() をファイルへリダイレクトしています。
import sys
# Save the current stdout so that we can revert sys.stdou after we complete# our redirectionstdout_fileno = sys.stdout
sample_input = ['Hi', 'Hello from Python', 'exit']
# Redirect sys.stdout to the filesys.stdout = open('output.txt', 'w')
for ip in sample_input:
# Prints to the redirected stdout (Output.txt)
sys.stdout.write(ip + ')
# Prints to the actual saved stdout handler
stdout_fileno.write(ip + ')
# Close the filesys.stdout.close()# Restore sys.stdout to our old saved file handlersys.stdout = stdout_fileno
|
出力 (output.txt が新しく作成されたファイルであると仮定します)
vijay@Python:~# python output_redirection.py
HiHello from Pythonexitroot@ubuntu:~# cat output.txt
HiHello from Pythonexit |
方法3: 明示的にファイルに出力する
print()`を呼び出す際に、fileキーワード引数を指定することで、出力するファイルを直接指定することができます。
例えば、以下のスニペットは、ファイル output.txt に印刷します。
print('Hi', file=open('output.txt', 'a'))
print('Hello from Python', file=open('output.txt', 'a'))
print('exit', file=open('output.txt', 'a'))
|
ファイルには3行が追加され、output.txtへの出力に成功しました!
コンテキストマネージャーの使用
しかし、この方法は、同じファイルに対して繰り返し open() を呼び出すことになるため、この状況を解決するための最良の方法とは言えません。
より良い方法は、コンテキストマネージャの with ステートメントを明示的に使用することで、自動的にファイルを閉じ、ファイルオブジェクトを直接使用することができます。
with open("output.txt", "a") as f: print('Hi', file=f)
print('Hello from Python', file=f)
print('exit', file=f)
|
これは前と同じ結果で、3つの行を output.txt に追加します。
しかし、同じファイルを何度も開くことがないので、より速くなりました。
この記事もチェック:Pythonでopenメソッドを使用してファイルを開く方法
方法4: logging モジュールを使用する
Pythonのloggingモジュールを使って、ファイルに出力することができます。
これは、ファイルストリームを明示的に変更することが最適な解決策ではない、方法2よりも好ましいです。
import logging
# Create the file# and output every level since 'DEBUG' is used# and remove all headers in the output# using empty format=''logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')
logging.debug('Hi')
logging.info('Hello from Python')
logging.warning('exit')
|
これはデフォルトで、3つの行を output.txt に追加します。
このように、ファイルへの印刷の推奨方法の1つである logging を使ってファイルに印刷しています。