使用Python在日志文件的头部添加新行

时间:2012-01-26 10:02:22

标签: python file-io newline

我正在尝试在日志文件中的日期戳前面添加一个新行。我有以下几个部分。

打开日志文件:

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

4 个答案:

答案 0 :(得分:6)

open()的python文档所示,默认模式为'r'表示读取,而不是'w'表示。尝试使用:

f = open("C:\Users\user\Desktop\Log.file", 'a')

打开您的日志文件进行写入(如果已存在则不删除它)

关于你的最终目标,即登录文件,您是否看过logging module,这将允许您使用日期,级别,PID和许多有用的东西格式化所有日志记录?

答案 1 :(得分:2)

f = open("C:\Users\user\Desktop\Log.file","w");

默认情况下,假定为'r',即阅读docs here

注意:'w'将覆盖现有文件。使用'a'追加

答案 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

希望这有帮助。