Oct-27-2018, 09:02 PM
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.
#and only writes what has been updated to the list from a previous logging function, but does not write prior
#info
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