String in Textdatei drucken

Ich benutze Python, um ein Textdokument zu öffnen:

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

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

text_file.close()

Ich möchte den Wert einer String-Variablen TotalAmount in das Textdokument einfügen. Kann mir bitte jemand sagen, wie das geht?

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

Wenn Sie einen Kontextmanager verwenden, wird die Datei automatisch für Sie geschlossen

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

Wenn Sie Python2.6 oder höher verwenden, sollten Sie str.format() verwenden.

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

Für Python2.7 und höher können Sie {} anstelle von {0} verwenden

In Python3 gibt es einen optionalen Parameter "file" für die Funktion "print".

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

Python3.6 führte f-strings als weitere Alternative ein

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

Wenn Sie mehrere Argumente übergeben wollen, können Sie ein Tupel verwenden

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

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

Kommentare (0)

Wenn Sie Python3 verwenden.

verwenden, können Sie Print Function verwenden:

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

Für python2

Dies ist das Beispiel für 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()
Kommentare (0)

Wenn Sie Numpy verwenden, können Sie eine einzelne (oder mehrere) Zeichenfolgen mit nur einer Zeile in eine Datei drucken:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
Kommentare (0)

Bei Verwendung des Pathlib-Moduls ist Einrückung't erforderlich.

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

Ab Python 3.6 sind f-Saiten verfügbar.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
Kommentare (0)