在 Python 3 中将字符串和日期写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20508689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write string and date to text file in Python 3
提问by JSJ
Trying to figure out how to out a guessing game score plus the date & time to a text file with a new line each time, keeping the old text.
试图弄清楚如何将猜谜游戏分数加上日期和时间添加到文本文件中,每次都换行,保留旧文本。
This is what I've got so far;
这是我到目前为止所得到的;
print('You scored %s.' % scr)
file = open("scr.txt", mode='w')
file.write('Printed string %s.\n' % scr)
This isn't working by the way - it's showing that an edit has been made to the text file but nothing is showing up in the text file - so I'm doing something wrong.
顺便说一下,这不起作用 - 它表明已经对文本文件进行了编辑,但文本文件中没有显示任何内容 - 所以我做错了什么。
I want the text file to read 'Printed string scrrecorded at date & time. As well as wanting a new line each time upon writing and keeping what has been written before.
我希望文本文件读取“在日期和时间记录的打印字符串scr ”。以及每次编写并保留之前编写的内容时都需要换行。
Thanks in advance. Any help would be greatly appreciated.
提前致谢。任何帮助将不胜感激。
回答by aIKid
Is this what you want?
这是你想要的吗?
from datetime import datetime
with open('scr.txt', 'a') as file:
file.write('Printed string %s. Recorded at: %s\n' % scr %datetime.now())
Demo:
演示:
>>> n = datetime.now()
>>> print("%s"%n)
2013-12-11 08:16:38.029267
回答by Michael
I think what you're missing is a flushand close. Python (like many other languages) uses buffers to manage data writes and batch writes to be more efficient. Try adding this after to see if you actually get some output in your file.
我认为你缺少的是一个flushand close。Python(与许多其他语言一样)使用缓冲区来管理数据写入和批量写入以提高效率。尝试在此之后添加它,看看您是否真的在文件中获得了一些输出。
file.close()
Additionally, to keep the previous data in your file, you'll want to open in append mode.
此外,要保留文件中的先前数据,您需要以追加模式打开。
file = open("scr.txt", "a")
This way, writes will append to the end of the file instead of truncating and rewriting your scores.
这样,写入将附加到文件的末尾,而不是截断和重写您的分数。
回答by abarnert
You're not calling file.close()anywhere. Until you do that (or file.flush()), there is no guarantee that anything will be written to the file; it could all be sitting around in a buffer somewhere.
你不会file.close()在任何地方打电话。在您这样做(或file.flush())之前,不能保证任何内容都会写入文件;它可能都坐在某个缓冲区中。
A better way to do this is to use a withstatement, so you don't have to remember to call close.
执行此操作的更好方法是使用with语句,因此您不必记住调用close.
This is explained indirectly by Reading and Writing Filesin the tutorial. The reference documentation explaining it in detail is scattered around the iodocs, which can be hard for a novice to understand.
本教程中通过读取和写入文件间接解释了这一点。详细解释它的参考文档分散在io文档周围,新手可能难以理解。
Also, opening the file in 'w'mode will replacethe entire file each time. You want to append to the existing file, which means you need 'a'mode. See the tutorial section Reading and Writing Filesor the opendocumentation for more details.
此外,以'w'模式打开文件每次都会替换整个文件。您想附加到现有文件,这意味着您需要'a'模式。有关更多详细信息,请参阅教程部分读取和写入文件或open文档。
Adding a new line, you've already got right, with the \nin the format string.
添加一个新行,您已经正确了,\n格式字符串中的 。
Finally, you can get the date and time with the datetimemodule. If you don't mind the default ISO date format, you can just format the datetimeobject as a string.
最后,您可以通过datetime模块获取日期和时间。如果您不介意默认的 ISO 日期格式,您可以将datetime对象格式化为字符串。
Putting it all together:
把它们放在一起:
import datetime
with open("scr.txt", mode='a') as file:
file.write('Printed string %s recorded at %s.\n' %
(scr, datetime.datetime.now()))

