[英]Is there a simple way to write multiple lines to a text 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))
您應該有一個包含所有收據信息的字符串:
def receipt():
str=''
str += '\n\n'
....
return str
然后您可以這樣稱呼它:
with open("bill.txt", "w") as bill:
bill.write(receipt())
bill.close()
而且我看到您在這里也遇到了一些問題,因為您沒有將name
和myBooks
推myBooks
()。 在運行腳本時,請確保這不是您的問題。
嘗試這個。 我沒有運行您的腳本,因為未定義任何變量
output = receipt()
file = open("sample.txt","w")
file.write(output)
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.