Python でファイルにテキストを追加する方法
胡金庫
2023年1月30日
Python
Python File
-
aモードでファイルにテキストを追加するためのfile.write -
Python 3 の
print関数にオプションのfileパラメーターを追加する - ファイルにテキストを追加する際に新しい行を追加する
このチュートリアル記事では、Python でファイルにテキストを追加する方法を紹介します。
a モードでファイルにテキストを追加するための file.write
ファイルにテキストを追加する場合は、ファイルを a モードまたは a+ モードで開くことができます。
destFile = r"temp.txt"
with open(destFile, "a") as f:
f.write("some appended text")
上記のコードは、ファイルの最後の文字の隣にテキスト some append text を追加します。たとえば、ファイルが this is the last sentence で終わる場合、追加後に this is the last sentencesome appended text というテキストになります。
指定されたパスにファイルが存在しない場合、ファイルを作成します。
Python 3 の print 関数にオプションの file パラメーターを追加する
Python 3 では、オプションの file パラメーターを有効にして、ファイルにテキストを出力できます。
destFile = r"temp.txt"
Result = "test"
with open(destFile, "a") as f:
print("The result will be {}".format(Result), file=f)
ファイルにテキストを追加する際に新しい行を追加する
新しい行にテキストを追加する場合は、追加されたテキストの後にキャリッジブレーク \r\n を追加して、次の追加されたテキストが新しい行に追加されることを保証する必要があります。
destFile = r"temp.txt"
with open(destFile, "a") as f:
f.write("the first appended text\r\n")
f.write("the second appended text\r\n")
f.write("the third appended text\r\n")
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
著者: 胡金庫
