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

发布于 2024-12-29 03:05:06 字数 412 浏览 2 评论 0原文

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

打开日志文件:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

晒暮凉 2025-01-05 03:05:06

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

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

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

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

As shown in the python documentation for open(), the default mode is 'r' for reading, not for 'w' for writing. Try to use :

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

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 ?

萌吟 2025-01-05 03:05:06
f = open("C:\Users\user\Desktop\Log.file","w");

默认情况下,假定为“r”,即阅读此处的文档

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

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

by default 'r' is assumed ie reading docs here

Note: 'w' will overwrite the existing file. Use 'a' to append

城歌 2025-01-05 03:05:06
open("C:\Users\user\Desktop\Log.file", "w")

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

忘你却要生生世世 2025-01-05 03:05:06

您需要 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文