0

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))
martineau
  • 119,623
  • 25
  • 170
  • 301
Cara
  • 3
  • 3
  • 2
    "What is the best/easiest way for me to write this ENTIRE module to another file?" - uh, what? I think you may have the wrong idea about what the word "module" means. – user2357112 Dec 07 '18 at 00:22
  • 1
    Do you mean to write all the things you're printing in the receipt file? – Aurora Wang Dec 07 '18 at 00:23
  • 1
    Possible duplicate of [write multiple lines in a file in python](https://stackoverflow.com/questions/21019942/write-multiple-lines-in-a-file-in-python) – U13-Forward Dec 07 '18 at 00:24
  • Aurora Wang- yes – Cara Dec 07 '18 at 00:34
  • U9-Forward if that is the same then I guess I just dont understand it. Would I need to clarify each one as "line 1","line 2", etc? or would it be more of pyhon already knows what I mean?? Im giving myself a headache! – Cara Dec 07 '18 at 00:36

2 Answers2

0

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.

Lê Tư Thành
  • 1,063
  • 2
  • 10
  • 19
-2

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()
Jlim2377
  • 61
  • 7
  • I was so excited when I saw this! then I tried it and got this: file.write(output) TypeError: write() argument must be str, not None – Cara Dec 07 '18 at 00:45
  • OK!! So this did work!! The only thing I had to change was output= str(receipt()) for the very first line. THANK YOU!! I'm to new to upvote it otherwise I would've – Cara Dec 07 '18 at 00:57
  • 2
    Sorry, since the `receipt()` function doesn't return anything, this answer could not possibly work—not even with what @Cara, the OP, claims have fixed it by doing. – martineau Dec 07 '18 at 02:31