我需要等待一个文件被创建,然后读入它。我有下面的代码,但确定它不能工作:
import os.path
if os.path.isfile(file_path):
read file in
else:
wait
有什么想法吗?
发布于 2014-02-13 14:25:29
一个简单的实现可以是:
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
异常。您还应该检查该路径是否为之后的文件,以避免某些不必要的异常。
发布于 2019-02-04 02:36:40
以下脚本将在下载文件或创建file_path后立即中断,否则在中断之前将等待文件下载或创建file_path的时间长达10秒。
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")
发布于 2014-02-13 15:15:39
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
https://stackoverflow.com/questions/21746750
复制相似问题