Is there a way to overwrite log files in python 2.x
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
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.