Python : clear a log file


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?


Asked By: Guillaume



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'):
Answered By: newtover

Just try to add a 'w' as argument:

fh = logging.FileHandler('debug.log', mode='w')

This worked for me.

Answered By: Steffen B

Building up on Steffen B’s answer: when using the logging.basicConfig function, one can also use this to rewrite the file instead of appending to it:

        # specify the filename
        filename=<PATH TO THE FILE>,
        # If filename is specified, open the file in this mode. Defaults to 'a'.

More information can be found in the dedicated section of the ‘logging’ module’s documentation.

Answered By: Viggar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.