70

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?

4
  • 2
    loop with a few second of time.sleep ?
    – falsetru
    Feb 13, 2014 at 6:24
  • while not os.path.isfile(): sleep(.1)?
    – g.d.d.c
    Feb 13, 2014 at 6:25
  • 2
    Don't use isfile to check the existence of the file, use exists and then do stat Feb 13, 2014 at 6:27
  • 1
    You can repeatedly check in a loop, but if you want something smarter you can use inotify: pypi.python.org/pypi/inotify/0.2.9 Apr 5, 2018 at 18:47

5 Answers 5

116

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.

5
  • @thefourtheye deceitful but fixed :p Feb 13, 2014 at 6:28
  • 3
    @thefourtheye: Does that matter? The program also waits forever if nothing is created at that path. Feb 13, 2014 at 6:41
  • @user2357112 Correct. How do we solve this problem? Async libraries? Feb 13, 2014 at 6:43
  • @thefourtheye: As a very simple solution, could you add in a counter so that the script quits after N attempts?
    – aim
    Apr 15, 2014 at 13:40
  • 4
    @aim: You could but we should keep the answer simple (lees than 10 lines without any variables) and let people customize it if they want. Apr 15, 2014 at 13:50
24

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")
0
3
import os
import time
file_path="AIMP2.lnk"
if  os.path.lexists(file_path):
    time.sleep(1)
    if os.path.isfile(file_path):
        fob=open(file_path,'r');
        read=fob.readlines();
        for i in read:
            print i
    else:
        print "Selected path is not file"
else:
    print "File not Found "+file_path
4
  • i did't find any error just i run just check file_path.
    – Sakam24
    Feb 13, 2014 at 7:26
  • @Sakam24 The problem is the os.path.lexists(...). It should be os.path.lexists(...). I beleive this is a typo, unless you edited os.py otherwise(?) Mar 25, 2016 at 4:25
  • @MaximeLorant I suppose it adds the variable definition and the reading of the file that would be useful is someone who is really new to programming encounters this answer and needs a functional example. Although his solution would only work for plain text files and under Python 2. Dec 22, 2016 at 11:08
  • Somewhat functional* The 1st check really should be a loop. Dec 22, 2016 at 11:29
2
import os.path
import time

file_present = False

while file_present == False:
    if os.path.isfile(file_path):
       # read file in
       file_present = True
       break

    time.sleep(5)
    
2
  • 3
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 31, 2021 at 4:54
  • 1
    There are four existing answers to this question, including a top-voted, accepted answer with nearly one hundred votes. Are you certain your solution hasn't already been given? If not, why do you believe your approach improves upon the existing proposals, which have been validated by the community? Offering an explanation is always useful on Stack Overflow, but it's especially important where the question has been resolved to the satisfaction of both the OP and the community. Help readers out by explaining what your answer does different and when it might be preferred. Jan 1, 2022 at 0:35
1

This code can check download by file size.

import os, sys
import time

def getSize(filename):
    if os.path.isfile(filename): 
        st = os.stat(filename)
        return st.st_size
    else:
        return -1

def wait_download(file_path):
    current_size = getSize(file_path)
    print("File size")
    time.sleep(1)
    while current_size !=getSize(file_path) or getSize(file_path)==0:
        current_size =getSize(file_path)
        print("current_size:"+str(current_size))
        time.sleep(1)# wait download
    print("Downloaded")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.