Hack Forums
[Python] File shows empty when python program is reading it - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] File shows empty when python program is reading it (/showthread.php?tid=5955058)



File shows empty when python program is reading it - FaberCastell - Mar 30, 2019

Basically i have a program running 24/7 and i open, write and append to the file with the program... I'm running program in the loop. At the of the loop it waits for 20seconds and then repeats the loop into infinite.

Problem is, that while i'm running the program and trying to open my file alerts.txt, it will show empty(even though it is not). If i exit the program, alerts.txt file WILL show the content.

How could i solve this. Basically i want to check the file when program is running&also insert into it manually...but it's showing empty.

f = open("alerts.txt", "r")
f.close
#somecode
f = open("alerts.txt", "w")
f.write("")
f.close
f = open("alerts.txt", "a")
#somecode
f.close


RE: File shows empty when python program is reading it - lockhead - Mar 30, 2019

It's probably because when you open a file in write mode all file contents gets deleted and also when you write or append to a file it doesn't get written immediately, it gets put into a buffer that is pushed through at some later time. I'm not sure exactly how this works but my guess is the buffer gets committed when the file is closed, the buffer is full or an exception gets thrown.. something like that anyways.
So to fix your issue make sure to immediately close the file immediately once you're done reading/writing to it at should decrease the likelihood of you opening the file in the explorer at the same time Python is using it.


RE: File shows empty when python program is reading it - Dark - Mar 30, 2019

when you open a file in w mode tthe second you write to it the prev contents is deleted, you should opeen files that you wish to write to with "a+" or just "a"


RE: File shows empty when python program is reading it - AeroBlue - Mar 30, 2019

Instead of "w" use "a" (append) mode with open function:


Code
with open("alerts.txt", "a") as f:



RE: File shows empty when python program is reading it - Oracle - Mar 30, 2019

If the file has content and u try to run the script with 'w' it will delete the content u need to replace the 'w' mode to 'a' ( append )