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

私はPythonを使ってテキストドキュメントを開いています。

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

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

text_file.close()

文字列変数 TotalAmount の値をテキストドキュメントに代入したいのです。誰かこの方法を教えてくれませんか?

ソリューション
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

コンテキストマネージャを使用している場合は、ファイルが自動的に閉じられます。

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

Python2.6以降を使用している場合は、str.format()を使用することをお勧めします。

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

Python2.7以降では、{0}の代わりに{}が使えます。

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

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

Python3.6 では f-strings が導入され、別の代替手段が用意されました。

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

複数の引数を渡したい場合は、タプルを使うことができます。

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

詳細: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python

解説 (0)

Python3を使用している場合。

の場合は、Print Functionが使えます。

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

python2の場合

これは、Python Print String To Text File の例です。

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256

def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))

def run():
    data = my_func()
    write_file(data)

run()
解説 (0)