[英]save the user input to existing text file everytime running the script python?
I'm trying to save the user input into one text file(I want to keep the record for a month).我正在尝试将用户输入保存到一个文本文件中(我想将记录保留一个月)。
But I'm not sure how to keep the old user input because every time I re-run the script new user input is automatically written on old-user input.但我不确定如何保留旧用户输入,因为每次我重新运行脚本时,新用户输入都会自动写入旧用户输入。
Is there any way to keep all the records regardless of running the script?无论运行脚本,有没有办法保留所有记录?
This is a simple example.这是一个简单的例子。
When I run the script once, I get the following result in output textile,当我运行脚本一次时,我在输出纺织品中得到以下结果,
2.5 2015-07-30
7 2015-07-30
1 2015-07-30
4 2015-07-30
5 2015-07-30
8.9 2015-07-30
but when I re-run the script, the above data is all being written by new user input.但是当我重新运行脚本时,上述数据都是由新用户输入写入的。 How can I make it so that my output text file maintains all the record regardless of running the script?
我怎样才能让我的输出文本文件保留所有记录,而不管脚本是否运行? This is my desired look of my output text file
这是我想要的输出文本文件的外观
2.5 2015-07-30
7 2015-07-30
1 2015-07-30
4 2015-07-30
5 2015-07-30
8.9 2015-07-30
4 2015-07-31
7 2015-07-31
2.4 2015-07-31
5 2015-07-31
1 2015-07-31
and this is the code that I've tried so far.这是我迄今为止尝试过的代码。
import datetime
with open("output.txt", 'w') as textfile:
while True:
input = raw_input("Enter: ")
if input == 'done':
break
textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')
You need to open the file in append mode to preserve the data already in the file.您需要以追加模式打开文件以保留文件中已有的数据。
'a'
opens the file for appending. 'a'
打开要追加的文件。
'a+'
opens the file for appending and creates the file if it does not exist. 'a+'
打开文件进行追加,如果文件不存在则创建该文件。
import datetime
with open("output.txt", 'a+') as textfile:
while True:
input = raw_input("Enter: ")
if input == 'done':
break
textfile.write(input+'\t'+ datetime.datetime.now().strftime("20%y-%m-%d")+'\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.