Skip to main content
 首页 » 编程设计

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

2025年05月04日28linjiqin

我每天为 9 个不同的文件运行一些 pandas 代码。目前,我有一个计划任务在特定时间运行代码,但有时我们的客户端没有按时将文件上传到 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。