Python wait and check if file is created completely by external program

file, python, python-3.x, thread-safety, time

Solution

This method apparently only works on Windows (ref. comment below), and relies on the fact that your external program only open and closes the file once during the creation of it.

import time

filename = 'my_file.txt'
while True:
    try:
        with open(filename, 'rb') as _:
            break
    except IOError:
        time.sleep(3)

If you want to set a maximum limit to the number of access attempts, you can do something like this:

import time

filename = 'my_file.txt'
max_i = 10

for i in xrange(max_i):
    try:
        with open(filename, 'rb') as _:
            break
    except IOError:
        time.sleep(3)
else:
    raise IOError('Could not access {} after {} attempts'.format(filename, str(max_i)))

Problem

I currently have external program outputting in the file in directory 'DIR'. Now if I want to see from python if the file is created completely, how can I check that and if done execute program. My research indicate that it could be done via ``` os.path.isfile(FILE_NAME) ``` but how do I keep on checking, in a way it does not mess-up other program. Here is something I had an idea about ? Please let me know how this can be achieved ? or is my template good enough ? ``` counter = 0; While os.path.isfile(FILE_NAME) == False: Time.Sleep(3) counter += 1 if counter < 5: # I guess we are good at this point ? ``` Thank you for your time and consideration.

Original source