Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to overwrite file
#1
Hi,
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.")
logging.info("It's sunny today.")
logging.debug("I had eggs for breakfast.")
Reply
#2
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.
Reply
#3
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?
Reply
#4
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+'):
    pass
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.
https://github.com/steveshambles?tab=repositories
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Openpyxl overwrite Linechart SamLiu 0 840 Nov-26-2022, 05:44 AM
Last Post: SamLiu
  Overwrite values in XML file with values from another XML file Paqqno 5 3,212 Apr-01-2022, 11:33 PM
Last Post: Larz60+
  Overwrite previous live data. Makada 2 2,303 Nov-07-2020, 07:40 PM
Last Post: Makada
  Dict overwrite previous list vincentspm 1 2,184 Mar-20-2019, 12:31 PM
Last Post: scidam
  overwrite data using openpyxl BNB 0 10,533 Jun-21-2017, 11:31 AM
Last Post: BNB

Forum Jump:

User Panel Messages

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