Tlač reťazca do textového súboru

Používam Python na otvorenie textového dokumentu:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

Chcem nahradiť hodnotu reťazcovej premennej TotalAmount do textového dokumentu. Môže mi niekto poradiť, ako to mám urobiť?

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

Ak používate kontextového správcu, súbor sa pre vás automaticky uzavrie

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

Ak používate Python2.6 alebo vyšší, je vhodnejšie použiť str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

V prípade Pythonu2.7 a vyššieho môžete namiesto {0} použiť {}

V jazyku Python3 je voliteľný parameter file funkcie print

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 zaviedol f-strings pre ďalšiu alternatívu

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)
Komentáre (9)

V prípade, že chcete odovzdať viacero argumentov, môžete použiť tuple

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

Viac: https://stackoverflow.com/questions/15286401/print-multiple-arguments-in-python

Komentáre (0)

Ak používate Python3.

potom môžete použiť Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

Pre python2

toto je príklad príkazu 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()
Komentáre (0)