Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and wait until a file exists to read it

Tags:

python

I need to wait until a file is created then read it in. I have the below code, but sure it does not work:

import os.path
if os.path.isfile(file_path):
    read file in
else:
    wait

Any ideas please?

like image 220
speedyrazor Avatar asked Feb 13 '14 06:02

speedyrazor


People also ask

How do I check to see if a file exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

How do you check file is exist or not in Python?

In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.

Which of the following expression can be used to check if the file exists and is also a regular file?

The Python isfile() method is used to find whether a given path is an existing regular file or not. It returns a boolean value true if the specific path is an existing file or else it returns false. It can be used by the syntax : os.

How do I check if a file exists in C++?

Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory or not.


2 Answers

A simple implementation could be:

import os.path
import time

while not os.path.exists(file_path):
    time.sleep(1)

if os.path.isfile(file_path):
    # read file
else:
    raise ValueError("%s isn't a file!" % file_path)

You wait a certain amount of time after each check, and then read the file when the path exists. The script can be stopped with the KeyboardInterruption exception if the file is never created. You should also check if the path is a file after, to avoid some unwanted exceptions.

like image 129
Maxime Lorant Avatar answered Oct 20 '22 07:10

Maxime Lorant


The following script will break as soon as the file is dowloaded or the file_path is created otherwise it will wait upto 10 seconds for the file to be downloaded or the file_path to be created before breaking.

import os
import time

time_to_wait = 10
time_counter = 0
while not os.path.exists(file_path):
    time.sleep(1)
    time_counter += 1
    if time_counter > time_to_wait:break

print("done")
like image 35
SIM Avatar answered Oct 20 '22 07:10

SIM