在继续操作之前检查文件列表是否存在



我每天都有一些熊猫代码运行9个不同的文件。目前,我有一个计划任务在特定时间运行代码,但有时我们的客户没有按时将文件上传到 SFTP,这意味着代码将失败。我想创建一个文件检查脚本。

缩短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)
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

另一种

使用map更简单的方法:

import os
file_names_list = ['file1', 'file2', 'file3']
if all(list(map(os.path.isfile,file_names_list))):
   # do something
else:
   # do something else!

最新更新