使用 Python 将新行添加到日志文件的头部
我正在尝试在日志文件中的日期戳前面添加新行。我有以下部分。
打开日志文件:
f = open("C:\Users\user\Desktop\Log.file")
在日期“25/01/2012”前面添加新行(唯一标识每个日志行)。
f.write("\n" + "25/01/2012")
错误:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
f.write('\n' + "25/01/2012")
IOError: File not open for writing
I'm trying to add a new line in front of a date stamp in a log file. I have the following parts.
Open log file:
f = open("C:\Users\user\Desktop\Log.file")
Add a new line in front of the date "25/01/2012" (uniquely identifies each log line).
f.write("\n" + "25/01/2012")
Error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
f.write('\n' + "25/01/2012")
IOError: File not open for writing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如 open() 的 python 文档所示,默认模式为 'r ' 表示阅读,而不是 'w' 表示写作。尝试使用 :
打开日志文件进行写入(如果已经存在,则不要删除它)
关于您的最终目标,即登录文件,您是否查看过 日志记录模块 它将允许您使用日期、级别、PID 和许多有用的东西来格式化所有日志记录?
As shown in the python documentation for open(), the default mode is 'r' for reading, not for 'w' for writing. Try to use :
to open your log file for writing (and not erasing it if it already exists)
Concerning your final goal, that is logging in files, did you have a look to the logging module which will allow you to format all your log record with date, level, PID and many usefull things ?
默认情况下,假定为“r”,即阅读此处的文档
注意:“w”将覆盖现有文件。使用 'a' 追加
by default 'r' is assumed ie reading docs here
Note: 'w' will overwrite the existing file. Use 'a' to append
但请看一下 http://docs.python.org/library/logging.html 用于使用 Python 进行日志记录。
编辑:更好:http://docs .python.org/howto/logging.html#logging-basic-tutorial
But please take a look at http://docs.python.org/library/logging.html for logging with Python.
Edit: Even better: http://docs.python.org/howto/logging.html#logging-basic-tutorial
您需要
f = open("C:\Users\user\Desktop\Log.file", "w")
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
希望这会有所帮助。
You need
f = open("C:\Users\user\Desktop\Log.file", "w")
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
Hope this helps.