Python : clear a log file

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

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:

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",
    )

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


Just try to add a 'w' as argument:

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

This worked for me.

Tags:

Python

Logging