Risposte:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Se si utilizza un gestore di contesto, il file viene chiuso automaticamente
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Se stai usando Python2.6 o versioni successive, è preferibile utilizzarlo str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Per python2.7 e versioni successive è possibile utilizzare {}invece di{0}
In Python3, esiste un fileparametro facoltativo per la printfunzione
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 ha introdotto le stringhe f per un'altra alternativa
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
TotalAmountis an int, entrambi %do %sfarà la stessa cosa.
with . . .: print('{0}'.format(some_var), file=text_file)sta lanciando: SyntaxError: invalid syntaxallo stesso segno ...
from __future__ import print_functionin cima al file. Si noti che ciò trasformerà tutte le istruzioni di stampa nel file nelle chiamate di funzione più recenti.
Nel caso in cui desideri passare più argomenti, puoi utilizzare una tupla
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Se stai usando Python3.
quindi è possibile utilizzare la 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()
Con l'utilizzo del modulo pathlib, il rientro non è necessario.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
A partire da Python 3.6, sono disponibili stringhe f.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")