在继续之前检查文件列表是否存在?
问题描述:
我有一些熊猫代码每天运行9个不同的文件。目前,我有一个计划的任务来在特定的时间运行代码,但有时文件还没有被我们的客户端上传到SFTP,这意味着代码将失败。我想创建一个文件检查脚本。在继续之前检查文件列表是否存在?
答
import os, time
filelist = ['file1','file2','file3']
while True:
list1 = []
for file in filelist:
list1.append(os.path.isfile(file))
if all(list1):
# All elements are True. Therefore all the files exist. Run %run commands
break
else:
# At least one element is False. Therefore not all the files exist. Run FTP commands again
time.sleep(600) # wait 10 minutes before checking again
all()检查列表中的所有元素是否为True
。如果至少有一个元素是False
,则返回False
。
答
缩短Farhan的答案。您可以使用列表理解,并且可以更加简化代码。
import os, time
while True:
filelist = ['file1', 'file2', 'file3']
if all([os.path.isfile(f) for f in filelist]):
break
else:
time.sleep(600)
这很好,谢谢。 –