打开一个文本文件而不清除其中的所有内容?
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
....(Somewhere else in the code)
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
我想知道如何保留可以写入的 log.txt 文件? 我希望能够打开一个 txt 文件,对其进行写入,然后能够稍后打开它并且之前写入的内容仍然存在。
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
....(Somewhere else in the code)
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
I was wondering how I can keep a log.txt file that I can write to?
I want to be able to open a txt file, write to it, then be able to open it later and have the contents of the previous write still be there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将
'w'
更改为'a'
,对于 追加模式。但您确实应该保持文件打开并在需要时写入。如果您重复自己,请使用logging
模块。Change
'w'
to'a'
, for append mode. But you really ought to just keep the file open and write to it when you need it. If you are repeating yourself, use thelogging
module.w(rite) 模式截断文件,a(pend) 模式添加到当前内容。
The w(rite) mode truncates a file, the a(ppend) mode adds to current content.
使用模式“a”进行追加。
Use mode 'a' for Append.
您需要以附加模式打开它
You need to open it in append mode