有没有一种简单的方法可以将多行内容写入文本文件?

2024-09-24 22:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个书店程序,它读取一个文本文件,你下订单,然后它将你的收据写入另一个文本文件。我把整件事都写了,却忘了把收据写进一个单独的文件里。将整个模块写入另一个文件的最佳/最简单方法是什么?你知道吗

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

Tags: 文件informatnumberfortotalsumtax
2条回答

您应该有一个字符串来包含所有收据信息:

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

你可以这样称呼它:

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

我看到你这里也有一些问题,你没有把namemyBooks推到receipt()。运行脚本时确保这不是您的问题。你知道吗

试试这个。我无法运行你的脚本,因为没有定义变量

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

相关问题 更多 >