Jag använder Python för att öppna ett textdokument:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Jag vill ersätta värdet av en strängvariabel TotalAmount
i textdokumentet. Kan någon berätta för mig hur jag ska göra detta?
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Om du använder en kontexthanterare stängs filen automatiskt för dig.
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Om du använder Python2.6 eller senare är det bättre att använda str.format()
.
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
För Python2.7 och högre kan du använda {}
istället för {0}
.
I Python3 finns det en valfri parameter file
för funktionen print
.
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introducerade f-strings för ett annat alternativ.
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
Om du vill skicka flera argument kan du använda en tupel
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Mer: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python
Om du använder Python3.
kan du använda Print Function :
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
För python2
Detta är ett exempel på Python Print String To Text File (Python skriver ut sträng till textfil)
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()