Udskriv streng til tekstfil

Jeg bruger Python til at åbne et tekstdokument:

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

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

text_file.close()

Jeg ønsker at erstatte værdien af en strengvariabel TotalAmount i tekstdokumentet. Kan nogen venligst lade mig vide, hvordan jeg gør dette?

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

Hvis du bruger en konteksthåndtering, lukkes filen automatisk for dig

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

Hvis du bruger Python2.6 eller højere, er det at foretrække at bruge str.format()

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

For python2.7 og højere kan du bruge {} i stedet for {0}

I Python3 er der en valgfri file-parameter til print-funktionen

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

Python3.6 introducerede f-strings for et andet alternativ

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

Hvis du ønsker at sende flere argumenter, kan du bruge en tupel

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

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

Kommentarer (0)

Hvis du bruger Python3.

så kan du bruge Print Function :

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

For python2

dette er et eksempel på 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()
Kommentarer (0)