Am'm folosind Python pentru a deschide un document text:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Vreau să substituie valoarea de un șir de variabile `TotalAmount în textul documentului. Poate cineva vă rog să-mi spuneți cum să fac asta?
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Dacă utilizați un context manager, fișierul este închis în mod automat pentru tine
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Daca're folosind Python2.6 sau mai mare, pentru a-l's de preferat să se utilizeze str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Pentru python2.7 și mai mare, puteți utiliza {}
în loc de {0}
În Python3, există un opțional "dosar" parametru "imprimare" funcția
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introdus f-siruri de caractere pentru o altă alternativă
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
În cazul în care doriți să treci mai multe argumente puteți utiliza un tuplu
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Mai mult: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python
Dacă utilizați Python3.
apoi, puteți utiliza Print Function :
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
Pentru python2
acesta este un exemplu de Python Print String Fișier Text
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()
Cu ajutorul pathlib module, indentare e't este necesar.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
Ca de python 3.6, f-siruri de caractere este disponibil.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")