What I want to do is to check if a file exists, and if it doesn't, perform an action, then check again, until the file exists and then the code continues on with other operations.
Asked
Active
Viewed 7,547 times
0
-
3please post your code so far – georg Jan 18 '13 at 17:50
-
2implement it as you think. You might be surprised... – Paul Collingwood Jan 18 '13 at 17:51
-
^^ answered my problem! :) – Adam Magyar Jan 24 '13 at 07:26
2 Answers
4
For simplicity, I would implement a small polling function, with a timeout for safety:
def open_file(path_to_file, attempts=0, timeout=5, sleep_int=5):
if attempts < timeout and os.path.exists(path_to_file) and os.path.isfile(path_to_file):
try:
file = open(path_to_file)
return file
except:
# perform an action
sleep(sleep_int)
open_file(path_to_file, attempts + 1)
I would also look into using Python built-in polling, as this will track/report I/O events for your file descriptor

Kyle
- 4,202
- 1
- 33
- 41
1
Assuming that you're on Linux:
If you really want to avoid any kind of looping to find if the file exists AND you're sure that it will be created at some point and you know the directory where it will be created, you can track changes to the parent directory using pynotify. It will notify you when something changes and you can detect if it's the file that you need being created.
Depending on your needs it might be more trouble than it's worth, though, in which case I suggest a small polling function like Kyle's solution.

Alberto Miranda
- 382
- 6
- 16
-
1I should also mention that pynotify implements an Observer pattern using short polling. See the [source code](https://github.com/seb-m/pyinotify/blob/master/python2/pyinotify.py#L1127) – Kyle Jan 18 '13 at 18:18