title: Having multiple Python programs reading and writing from a single text file is causing issues with "blank reads". Some ideas and questions
body: <p>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.</p>
  <p>For reference, here is how I have my programs set up. Here is the first program 1, which writes to the file:</p>
  <pre><code>while 1==1: #to make an endless loop
      file = open(&quot;demo.txt&quot;, &quot;w&quot;)
      data = file.write('data goes here')
      file.close()
  
      time.sleep(360)
  </code></pre>
  <p>and the reader program:</p>
  <pre><code>while 1==1: #for the endless loop
      file = open(&quot;demo.txt&quot;, &quot;r&quot;)
      data = file.read()
      file.close()
      time.sleep(0.1)
  </code></pre>
  <p>The above works great until they end up reading/writing at the same time.</p>
  <p>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:</p>
  <pre><code>file = open(&quot;demo.txt&quot;, &quot;r&quot;)
  data = file.read()
  while data == '':
      file = open(&quot;demo.txt&quot;, &quot;r&quot;)
      data = file.read()
  file.close()
  </code></pre>
  <p>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.</p>
  <p>Thanks!</p>
  <p>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.</p>