Python Imprimir Cadena A Archivo De Texto


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 introducir la cadena llamada "totalAmount" en el documento de texto. ¿Puede alguien por favor dejarme saber cómo hacer esto?

Author: Eric Leschinski, 2011-03-07

6 answers

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

Si utiliza un administrador de contexto, el archivo se cierra automáticamente para usted

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

Si estás usando Python2. 6 o superior, es preferible usar 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)
 833
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-02 03:57:40

En caso de que desee pasar varios argumentos, puede usar 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: Imprimir múltiples argumentos en python

 29
Author: user1767754,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:35

Si está utilizando numpy, la impresión de una sola (o multiplicar) cadenas a un archivo se puede hacer con una sola línea:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
 14
Author: Guy s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 06:56:32

Este es el ejemplo de Python Imprimir Cadena A Archivo de texto

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, 'wb') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()
 7
Author: Rajiv Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 07:21:58

Con el uso del módulo pathlib, la sangría no es necesaria.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

A partir de python 3.6, las cadenas f están disponibles.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
 3
Author: naoki fujita,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-30 05:23:32

Una forma más fácil de hacerlo en Linux y Python,

import os
string_input = "Hello World"
os.system("echo %s > output_file.txt" %string_input)

(O)

import os
string_input = "Hello World"
os.system("echo %s | tee output_file.txt" %string_input)
 0
Author: Vikram S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 09:23:24