Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

File shows empty when python program is reading it

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
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.
[Image: 0DvFxnA.gif]
Donate: 3ABKRghau93ziRaDfVwiiwtjky3i1gLrKn
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"
Instead of "w" use "a" (append) mode with open function:


Code
with open("alerts.txt", "a") as f:
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 )


Possibly Related Threads...
Thread / Author Replies Views Last Post
by Neo_KaiserAug 10, 2025 02:36 PM 0 109 Aug 10, 2025 02:36 PM
Last Post: Neo_Kaiser
[Python] by Bass_ReevesAug 20, 2023 01:44 AM 9 632 Aug 20, 2023 01:44 AM
Last Post: Lucky4L
[C#] by notahackermanApr 27, 2020 10:05 PM 14 347 Apr 27, 2020 10:05 PM
Last Post: Accord