我正在尝试在日志文件中的日期戳前面添加一个新行。我有以下几个部分。
打开日志文件:
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
答案 0 :(得分:6)
如open()的python文档所示,默认模式为'r'表示读取,而不是'w'表示。尝试使用:
f = open("C:\Users\user\Desktop\Log.file", 'a')
打开您的日志文件进行写入(如果已存在则不删除它)
关于你的最终目标,即登录文件,您是否看过logging module,这将允许您使用日期,级别,PID和许多有用的东西格式化所有日志记录?
答案 1 :(得分:2)
答案 2 :(得分:1)
open("C:\Users\user\Desktop\Log.file", "w")
但请查看http://docs.python.org/library/logging.html以使用Python进行日志记录。
修改:更好:http://docs.python.org/howto/logging.html#logging-basic-tutorial
答案 3 :(得分:0)
您需要f = open("C:\Users\user\Desktop\Log.file", "w")
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
希望这有帮助。