'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
Solution 1:[1]
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
Solution 2:[2]
The actual answer is to add the filemode = 'w' AND force = True parameter to basicConfig. What seems to be happening is that default handlers are setting the filemode to a for append. With filemode already set, logging doesn't bother to apply your requested filemode of w for write. Adding the force parameter disables all default handlers and uses all the parameters you specified instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | benson23 |
