Tekenreeks naar tekstbestand afdrukken

Ik gebruik Python om een ​​tekstdocument te openen:

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

Ik wil de waarde van een stringvariabele TotalAmountin het tekstdocument vervangen. Kan iemand me vertellen hoe ik dit moet doen?


Antwoord 1, autoriteit 100%

Het wordt sterk aangeraden om een ​​contextmanager te gebruiken. Als voordeel wordt ervoor gezorgd dat het bestand altijd gesloten is, wat er ook gebeurt:

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

Dit is de expliciete versie (maar onthoud altijd dat de contextmanager-versie van hierboven de voorkeur heeft):

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

Als u Python2.6 of hoger gebruikt, heeft het de voorkeur om str.format()

te gebruiken

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

Voor python2.7 en hoger kunt u {}gebruiken in plaats van {0}

In Python3 is er een optionele parameter filevoor de functie print

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

Python3.6 introduceerde f-stringsvoor een ander alternatief

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

Antwoord 2, autoriteit 4%

Als u meerdere argumenten wilt doorgeven, kunt u een tuple gebruiken

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

Meer: Print meerdere argumenten in python


Antwoord 3, autoriteit 3%

Als je Python3 gebruikt.

dan kun je Afdrukfunctie:

gebruiken

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

Voor python2

dit is het voorbeeld van 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()

Antwoord 4, autoriteit 2%

Als u numpy gebruikt, kunt u met slechts één regel een enkele (of meerdere) tekenreeks naar een bestand afdrukken:

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

Antwoord 5

Met het gebruik van de pathlib-module is inspringen niet nodig.

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

Vanaf python 3.6 is f-strings beschikbaar.

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

Antwoord 6

gebruik van f-stringis een goede optie omdat we multiple parameterskunnen plaatsen met syntaxis zoals str,

bijvoorbeeld:

import datetime
now = datetime.datetime.now()
price = 1200
currency = "INR"
with open("D:\\log.txt","a") as f:
    f.write(f'Product sold at {currency} {price } on {str(now)}\n')

LEAVE A REPLY

Please enter your comment!
Please enter your name here

13 − 6 =

Other episodes