Python:清除日志文件

时间:2012-01-17 17:27:49

标签: python logging clear

我开发了一个客户端 - 服务器应用程序,我已登录服务器,因此我使用了日志记录模块。我想在服务器中创建一个命令来清除文件。

我使用os.remove()进行测试,但之后,日志不起作用。

你有什么想法吗?

感谢。

4 个答案:

答案 0 :(得分:38)

最好截断文件而不是删除它。最简单的解决方案是从清除功能重新打开文件进行写入并关闭它:

with open('yourlog.log', 'w'):
    pass

答案 1 :(得分:2)

尝试添加一个“w”作为参数:

fh = logging.FileHandler('debug.log', "w")
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)

这对我有用。

答案 2 :(得分:2)

以 Steffen B 的回答为基础:使用 logging.basicConfig 函数时,还可以使用它来重写文件而不是附加到文件中:

logging.basicConfig(
        # specify the filename
        filename=<PATH TO THE FILE>,
        # If filename is specified, open the file in this mode. Defaults to 'a'.
        filemode="w",
    )

可以在in the dedicated section of the 'logging' module's documentation找到更多信息。

答案 3 :(得分:1)

试试这个

>>> with open("gre.txt", "w") as file:
...  file.truncate()
...
>>>

更新:

file.truncate()没有必要。你可以pass

相关问题