HOWTO · Python
Python でファイルにテキストを追加する方法
Python 2.7 または 3 でファイルにテキストを追加するサンプルコードを示しています。
このチュートリアル記事では、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")