Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using python2.x logging module, like,

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 logs.log file for each execution of the script, currently it just appends to old logs. I know the below code will overwrite, but if there is a way to do it via logging config, it'll look better.

with open("logs.log", 'w') as file:
  pass
like image 621
user3366706 Avatar asked Feb 16 '16 21:02

user3366706


People also ask

How do you overwrite a log in Python?

The filemode can be changed to write mode, which will overwrite the previous logs and only save the current ones. Since the filemode is set to w , this means that the log file will be opened in write mode each time basicConfig() is run, which will ultimately overwrite the file.

How do you overwrite a file if it already exists in Python?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it.


2 Answers

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 the big table explaining all options):

filemode: Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to ‘a’).

like image 89
SethMMorton Avatar answered Sep 19 '22 10:09

SethMMorton


Both

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

and

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

always append in Python 2.7, on both Windows and Linux

like image 45
Reddy Kilowatt Avatar answered Sep 19 '22 10:09

Reddy Kilowatt