How to overwrite file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to overwrite file (/thread-25810.html) |
How to overwrite file - SriRajesh - Apr-12-2020 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.") RE: How to overwrite file - deanhystad - Apr-13-2020 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. RE: How to overwrite file - SriRajesh - Apr-14-2020 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? RE: How to overwrite file - steve_shambles - Apr-14-2020 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+'): passI 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. |