Search code examples
pythontext-fileswritetofile

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))

Solution

  • 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()