Ik gebruik Python om een tekstdocument te openen:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Ik wil de waarde van een string variabele TotalAmount
in het tekstdocument substitueren. Kan iemand mij laten weten hoe ik dit moet doen?
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Als u een context manager gebruikt, wordt het bestand automatisch voor u gesloten
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Als u'Python2.6 of hoger gebruikt, verdient het de voorkeur om str.format()
te gebruiken
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Voor python2.7 en hoger kun je {}
gebruiken in plaats van {0}
In Python3, is er een optionele file
parameter voor de print
functie
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduceerde f-strings voor een ander alternatief
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
Indien u meerdere argumenten wenst door te geven kan u een tupel gebruiken
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Meer: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python
Als u Python3 gebruikt.
dan kunt u Print Functie gebruiken:
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
Voor python2
dit is het voorbeeld van 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()