Python Forum

Full Version: Problem with file not saving current output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have an issue with writing to a file in a for loop. I am appending all of the logged characters to a list. The list has an active listener attached to it, so is actively appending.

When I go to write this list to a file, it works great. However, I am having a problem with closing the file and saving the information. Once the file closes, the information is lost and the file only saves with the newest character of the list after the cutoff limit.

So basically, I need a way to save the file before I close it, so it will write all of the contents to a file.
The "logs" list is being updated by the on_press(key) function, and it's continiually appenidng characters to the Logs list.
When the file writes, it writes fine. When it closes, it closes and loses all of the information that was in the logs list, hence I get an empty TXT file.


def on_press(key):
    logging.info(str(key))
    logs.append(key)
    with open('your_log.txt', 'w') as f:
        if len(logs) < 10:
            for item in logs:
                f.write('%s\n' % item)
        else:
            if len(logs) > 10:
                for item in logs:
                    f.write('%s\n' % item)   #will write the length of the log list which is 9 characters
                    if len(logs) > 10:     
                        break
                    f.close()
#if the length of the log list goes above 10, then the file closes
#and only writes what has been updated to the list from a previous logging function, but does not write prior
#info
Admittedly I just glanced your code quickly, but I suspect your placing of f.close() might be problematic. It is called only if the else clause is executed and only if break (on line 13) does not occur. Look into that.

You want to consider using context manager to work with files. It will close the file automatically after the code (inside the context manager) is finished processing. You can search online, or this forums, since the topic was brought up many times in the past.

By the way, what happens if len(logs) is 10)?
I have messed around with the if/else quite a bit. I'll have to revisit.

The 10 is just a test number - I'm trying to achieve closing the file when the
Lost reached a certain number of characters.