Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to overwrite file
I am writing some log file, and when I run each time I want to flush out everything (don't want to keep any previous data) I use the below code, but it is not working, I also tried with "w+", "a", and "a+" mode, still does not work. Kindly help how to fix it.

import logging
# log messages to a file, ignoring anything less severe than ERROR
logging.basicConfig(filename='myprogram.log', filemode = 'w', level=logging.ERROR)

# these messages should appear in our file
logging.error("The washing machine is leaking!")
logging.critical("The house is on fire!")

# but these ones won't
logging.warning("We're almost out of milk.")"It's sunny today.")
logging.debug("I had eggs for breakfast.")
What are you using (os, python version, dev tools). When I run this on my Windows desktop with Python 3.8.2 I cannot get it to append, regardless of the filemode.
Windows7, python version: 3.6.8 |Anaconda 4.3.1 (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
DO I need to import anything or do anything?
I had the same problem with my Sync-It app this week.
I used "W+" for all the writes and to clear the log, and setting up the log.

I used this to clear the log:
with open('syncit.log', 'w+'):
I did this on start up and after the log details had been displayed
and I didn't need the data any more.

Then I had the problem that clearing it this way (on my Windows computer at least)
it left a lot of "NUL" characters that confused my code when I tried
to read the lines into strings.

To remove these I found a re solution on stackoverflow:

line = re.sub(r'[\x00-\x1F]+', '', line) # Strip some non ASCII.
and all my problems were solved.

See my GitHub repositories for Sync-It code if you want.
I'm working on an update at the moment V0.37 with much improved code and a few new features
should be uploading it to GitHub tomorrow sometime.

Possibly Related Threads…
Thread Author Replies Views Last Post
  Overwrite previous live data. Makada 2 651 Nov-07-2020, 07:40 PM
Last Post: Makada
  Dict overwrite previous list vincentspm 1 1,048 Mar-20-2019, 12:31 PM
Last Post: scidam
  overwrite data using openpyxl BNB 0 8,137 Jun-21-2017, 11:31 AM
Last Post: BNB

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020