I have 2 python(3.9) programs. One program writes to a text file, and another reads from that same text file to occasionally to populate data onto a website. Sometimes the unfortunate occurrence happens where the reading and writing ends up happening simultaneously, so the reading program ends up with blank data. The result looks like an empty string(such as ' '), and blank data throws a wrench in the flow of my setup.
For reference, here is how I have my programs set up. Here is the first program 1, which writes to the file:
while 1==1: #to make an endless loop
file = open("demo.txt", "w")
data = file.write('data goes here')
file.close()
time.sleep(360)
and the reader program:
while 1==1: #for the endless loop
file = open("demo.txt", "r")
data = file.read()
file.close()
time.sleep(0.1)
The above works great until they end up reading/writing at the same time.
Is there an elegant way to fix this? I've come up an idea that seem to work - having the reader program use a while loop to check for blank data:
file = open("demo.txt", "r")
data = file.read()
while data == '':
file = open("demo.txt", "r")
data = file.read()
file.close()
This seems to work, but is there a better way? Maybe an inherent way for python to sort out reading from a file that is already open in another program? Any ideas would be appreciated.
Thanks!
EDIT: after the comments below I've done a bit of reading on read/write locks - seems like multithreading is the common solution to this problem. I'm trying to avoid threading, looking for something simple and succinct. The os.rename idea below seems like the right idea.