Python打开一个txt文件而不清除其中的所有内容? [英] Python Open a txt file without clearing everything in it?

查看:775
本文介绍了Python打开一个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()

我想知道如何保存一个我可以写入的log.txt文件?
我希望能够打开一个txt文件,写入它,然后能够稍后打开它,并且上一次写入的内容仍然存在。

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.

推荐答案

'w'更改为'a',用于< a href =http://docs.python.org/library/functions.html#open =noreferrer>追加模式。但是你真的应该保持文件打开并在需要时写入它。如果您重复自己,请使用 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 the logging module.

这篇关于Python打开一个txt文件而不清除其中的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆