python-检查并等待直到文件存在以读取我

我需要等待,直到创建了一个文件,然后将其读入。我有以下代码,但请确保它不起作用:

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

有什么想法吗?

speedyrazor asked 2020-08-11T22:00:03Z
4个解决方案
68 votes

一个简单的实现可以是:

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)

每次检查后,您都需要等待一段时间,然后在路径存在时读取文件。 如果从未创建该文件,则可以使用KeyboardInterruption异常停止该脚本。 您还应该检查该路径是否位于该文件之后,以避免某些不必要的异常。

Maxime Lorant answered 2020-08-11T22:00:14Z
7 votes

一旦下载文件或创建了file_path,以下脚本将立即中断,否则它将在中断之前等待长达10秒钟的时间来下载文件或创建file_path。

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")
SIM answered 2020-08-11T22:00:34Z
3 votes
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
Sakam24 answered 2020-08-11T22:00:49Z
0 votes

此代码可以按文件大小检查下载。

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")
    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")
Nori answered 2020-08-11T22:01:09Z
translate from https://stackoverflow.com:/questions/21746750/check-and-wait-until-a-file-exists-to-read-it