1

I am running the following code very often to write to files from Python using the following:

def function():
    file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
    fifo = open(file, 'w')
    if (os.path.isfile(file) and os.access(file, os.W_OK)):
        fifo.write("stuff")
        fifo.close()
    else:
        time.sleep(1)
        function()

Unfortunately, I get the following error (not all the time):

IOError: [Errno 2] No such file or directory

This is self-explanatory, but I do not understand then why all the precautions do not work, like isfile or access..W_OK ? How do I avoid having this issue?

Also, the slower the machine, the less often the error is encountered.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Boris Mocialov
  • 3,439
  • 2
  • 28
  • 55

1 Answers1

0

See also "LBYL vs EAFP in Java?":

Instead of checking if the action is ok (LBYL), you should do an EAFP approach. Just do what you want to do and check if it has worked correctly.

Besides, better don't call function() recursively, it might lead to a stack overflow if the error persists.

Better do

def function():
    file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
    while True:
        try:
            with open(file, 'w') as file: # automatically closes...
                file.write("some stuff")
        except IOError, e:
            time.sleep(1)
            continue
        break # the while loop
Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217