Estoy usando Python para abrir un documento de texto:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Quiero sustituir el valor de una variable de cadena TotalAmount
en el documento de texto. ¿Puede alguien decirme cómo hacerlo?
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Si utiliza un gestor de contexto, el archivo se cierra automáticamente por usted
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Si utiliza Python 2.6 o superior, es preferible utilizar str.format()
.
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Para python2.7 y superior puedes usar {}
en lugar de {0}
.
En Python3, hay un parámetro opcional file
para la función print
.
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introdujo f-strings para otra alternativa
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
En caso de que quieras pasar varios argumentos puedes utilizar una tupla
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Más: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python
Si estás usando Python3.
entonces puede utilizar Función de impresión :
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
Para python2
este es el ejemplo 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()