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

3

20

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
Sites answered 16/2, 2016 at 21:58 Comment(0)
M
35

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’).

Monotonous answered 16/2, 2016 at 22:3 Comment(2)
Note that "filemode" is the keyword "mode" if you use DictConfig. Example: ` "handlers": { "file": { "class": "logging.FileHandler", "formatter": "form02", "level": "INFO", "filename": "logs.log", "mode": "w", # Overwrite file if it exists }, }, `Macon
I don't think this works anymore. 'w' will add truncation line and append the content. Just tested in Python 3.10. Here is documentaion: docs.python.org/3/library/functions.html#openDibb
S
4

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.

Stratification answered 24/2, 2022 at 22:35 Comment(1)
Thanks! This should be the correct answer in multiple questions here on SO.Vermination
B
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

Buhrstone answered 21/9, 2018 at 23:9 Comment(1)
I'm also seeing the same behavior in Python 3.6. This just doesn't seem right- I'm passing filemode='w' in all cases.Buhrstone

© 2022 - 2024 — McMap. All rights reserved.