Stampa una stringa in un file di testo

Sto usando Python per aprire un documento di testo:

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

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

text_file.close()

Voglio sostituire il valore di una variabile stringa TotalAmount nel documento di testo. Qualcuno può per favore farmi sapere come fare questo?

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

Se usi un gestore di contesto, il file viene chiuso automaticamente per te

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

Se stai usando Python2.6 o superiore, è preferibile usare str.format().

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

Per python2.7 e superiori si può usare {} invece di {0}.

In Python3, c'è un parametro opzionale file alla funzione print.

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

Python3.6 ha introdotto f-strings per un'altra alternativa

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

Nel caso si vogliano passare più argomenti si può usare una tupla

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

Di più: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python

Commentari (0)

Se state usando Python3.

allora potete usare Funzione di stampa :

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

Per python2

questo è l'esempio di 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()
Commentari (0)