こんにちは。
本日はPythonメモです。
概要
print()を使用してファイルへの出力を行ってみます。
write()を使用したファイル出力については
以下の記事で記載しています。
【Python】ファイルの読み書き - なんだかGoodVibes
ファイルへの出力
t = 'hello bob.' with open('./out.txt', mode='wt', encoding='utf-8') as f: print(t, file=f)
出力結果は以下です。
hello bob.
次に、リストのデータをファイルへ出力してみます。
l = ['hello bob', 'hello world'] with open('./out.txt', mode='wt', encoding='utf-8') as f: print(*l, file=f)
出力結果は以下です。
hello bob hello world
print()はデフォルトで、区切り文字にスペース、末尾に改行となっているので、
それらを変更して出力してみます。
l = ['hello bob', 'hello world'] with open('./out.txt', mode='wt', encoding='utf-8') as f: print(*l, file=f, sep='\n', end='!')
実行結果は以下です。
hello bob hello world!
各要素の区切り文字が「改行」、末尾が「!」に変更することができました。
以上です。