Python : clear a log file

2019-03-18 01:24发布

I develop a client-server application and I have log in the server, so I use the logging module. I would like to create a command in the server to clear the file.

I have test with os.remove() but after, the log doesn't work.

Do you have an idea?

Thanks.

2条回答
欢心
2楼-- · 2019-03-18 01:37

Try this

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

UPDATE:

file.truncate() is not necessary. You can just pass

查看更多
Lonely孤独者°
3楼-- · 2019-03-18 01:47

It might be better to truncate the file instead of removing it. The easiest solution is to reopen the file for writing from your clearing function and close it:

with open('yourlog.log', 'w'):
    pass
查看更多
登录 后发表回答