0

I have a while True loop in a Python script and I would like to write only one line in some files constantly. Next to, I have an other script that read the content (also constantly) of each file. The problem is that when I read, sometime, files are empty beacause the write script is writing in the files.

Here is my write script

while True:
for file in files:
    thefile = open(file, "w+")
    thefile.write("myLine")
    thefile.close()

And my read script

while True:
for file in files:
    thefile = open(file, "r")
    print thefile.read()
    thefile.close()

Have you got an idea ?

  • 2
    http://stackoverflow.com/questions/186202/what-is-the-best-way-to-open-a-file-for-exclusive-access-in-python – Henry Heath Apr 18 '17 at 13:11
  • There are better ways for two programs to communicate than via files. You might want to research interprocess communication; sockets, pipes, etc. – Aran-Fey Apr 18 '17 at 13:13
  • This is a [race condition](https://en.wikipedia.org/wiki/Race_condition). There is no way to control the timing on file reads and writes from different processes. You should either be [locking files](https://en.wikipedia.org/wiki/File_locking) to ensure that reads only happen after writes, or, preferrably, using a different interprocess communication mechanism such as a pipe. – Pedro Castilho Apr 18 '17 at 13:17

0 Answers0