简体   繁体   English

Append 放到 .txt 文件的底部

[英]Append onto bottom of .txt file

i have a script which takes and records payments.我有一个脚本来记录付款。 I have created a.txt file to hold transaction information and the code looks like:我创建了一个 .txt 文件来保存交易信息,代码如下:

payment_file = open('Payments.txt', 'w')
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close() 

As an example when i open the txt it will appear as例如,当我打开 txt 时,它将显示为

Card no: XXXX-XXXX-XXXX-1234 | Amount: £15.00

However once one payment is finished the script loops back to the start allowing for another payment to be made but once the next payment is made and you open the.txt the old payment just gets replaced by the most recent one, how would you make sure the payments just get appended underneath eachother但是,一旦完成一笔付款,脚本将循环回到开始,允许进行另一笔付款,但是一旦进行下一笔付款并打开.txt,旧付款就会被最近的付款替换,您将如何确保付款只是在彼此下方附加

You need to change this:你需要改变这个:

payment_file = open('Payments.txt', 'a')          # ----------> Here a means appending and not overwriting the existing content.
payment_file.write('Card no: {} | Amount: £{}\n'.format('XXXX-XXXX-XXXX-' + card_number[-4:], "{:,.2f}".format(amount)))
payment_file.close() 

You need to use append.您需要使用 append。 Append adds data to the end of files. Append 将数据添加到文件末尾。 Write writes over the whole file.写入整个文件。 Please see the following Python documentation for reading and writing to files: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files请参阅以下 Python 文档以读取和写入文件: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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