I'm usando Python para abrir um documento de texto:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Eu quero substituir o valor de uma variável string TotalAmount
no documento de texto. Alguém pode me dizer como fazer isso?
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Se você usar um gerenciador de contexto, o arquivo é fechado automaticamente para você
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Se você'estiver utilizando Python2.6 ou superior, ele's preferem utilizar str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Para python2.7 ou superior, você pode utilizar {}
ao invés de {0}
.
Em Python3, há um parâmetro opcional file
para a função `print
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduziu f-strings para outra alternativa
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
No caso de querer passar vários argumentos, pode usar um tuple
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Mais: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python
Se você estiver usando Python3.
então você pode usar Função de Impressão :
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
Para python2
este é o exemplo de 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()