文字列をテキストファイルに印刷する 質問する

文字列をテキストファイルに印刷する 質問する

TotalAmount次のコードでは、 Python を使用して、文字列変数の値をテキスト ドキュメントに置き換えます。

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

これを行う方法?

ベストアンサー1

コンテキスト マネージャーを使用することを強くお勧めします。利点として、どのような場合でもファイルが常に閉じられていることが保証されます。

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

これは明示的なバージョンです (ただし、常に上記のコンテキスト マネージャー バージョンを優先する必要があることに注意してください)。

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

Python2.6以上を使用している場合は、str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

python2.7以降では、{}代わりに{0}

Python3では関数fileにオプションのパラメータがありますprint

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6が導入されましたf弦別の選択肢として

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

おすすめ記事