Is there a way to overwrite log files in python 2.x

I am using the python2.x logging module for example

logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='logs.log', level=logging.INFO) 

I want my program to overwrite the logs.log file for each script execution, currently it just adds to the old logs. I know that the code below will overwrite, but if there is a way to do this using the registration configuration, it will look better.

 with open("logs.log", 'w') as file: pass 
+6
source share
1 answer

Add the filemode option to basicConfig :

 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='logs.log', filemode='w', level=logging.INFO) 

From the logging documentation for the basicConfig method (in a large table explaining all the parameters):

filemode : Indicates file open mode if file name is specified (if file is not specified, file defaults to 'a).

+9
source

All Articles