简体   繁体   中英

Is there a simple way to write multiple lines to a text file?

I'm writing this bookstore program that reads a text file, you place your order, and then it writes your receipt to a different text file. I wrote the whole thing forgetting I needed to write the receipt to a separate file. What is the best/easiest way for me to write this entire module to another file?

def receipt():
    sum=0.0
    print("\n\n")
    print("*"*70)
    print("\tThank you {} for your purchase at The Book 
    Store!".format(name))
    print("*"*70)
    print("\nQty\t\tItem\t\tPrice\t\tTotal\n")
    for i in range(len(myBooks)):
        print(myBooks[i][0],"\t",myBooks[i][1],"\t",myBooks[i][2],"\t\t",myCost[i])
    for number in myCost:
        sum = sum + number

    print("\n\nSubtotal:     ${}".format(sum))
    tax = round(sum * .076,2)
    total = round(sum + tax,2)
    print("Tax:          ${}".format(tax))
    print("Total:        ${}".format(total))

You should have a string to contain all receipt information:

def receipt():
    str=''
    str += '\n\n'
    ....
    return str

Then you can call it like:

with open("bill.txt", "w") as bill:
    bill.write(receipt())
bill.close()

And I saw you also have some problems here are you doesn't push the name and myBooks to receipt(). Make sure it's not your problem when you run your script.

Try this. I can't run your script because no variables are defined

output = receipt()
file = open("sample.txt","w")
file.write(output)
file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM