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
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.
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.
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’).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With