python - 找不到文件时如何继续循环

标签 python

我正在尝试打印用户设置的日期范围内的文件列表。

这是我的示例文件:注意文件中没有“2015-01-01”

enter image description here

如果我输入从 2015-01-022015-01-05 的范围,它将打印文件列表。但是,如果我从 2015-01-01 输入到 2015-01-05 它将导致错误:

OSError: (2, 'No such file or directory', '\\2015-01-01')

是否可以使用 try-except-pass 或 continue 以便我的循环仍将继续并打印 2015-01-022015-01-05。并拒绝找不到文件。

这是我当前的代码:

FileNameList = []
date = start_date
while date <= end_date:
    folder_name = date.strftime(DATE_FORMAT)
    data_folder = path.join(pathDir, folder_name)
    #print data_folder  

    for filefolder in os.listdir(data_folder):      
        filefolder = data_folder + "\\" + filefolder

    FileNameList.append(filefolder)

    date += delta_one_day

for filefolder in FileNameList:
    for file in os.listdir(filefolder):
        if ".txt" in file:
            filename = filefolder + "\\" + file 
            print filename      

最佳答案

您可以尝试/排除循环,但更好的解决方案可能是首先仅将现有目录附加到您的列表中:

# your code and while loop here

if os.path.isdir(data_folder):
    for filefolder in os.listdir(data_folder):      
        filefolder = data_folder + "\\" + filefolder

    if os.path.isdir(filefolder):
        FileNameList.append(filefolder)

for 循环放在 try/except block 中可能会有点困惑,因为如果发生异常,您将无法从中断处继续循环。但如果你确实想坚持使用 EAFP strategy :

for filefolder in FileNameList:
    try:
        files = os.listdir(filefolder)
    except OSError:
        # You could log/print a warning here if you need.
        continue
    for file in files:
        if ".txt" in file:
            filename = filefolder + "\\" + file 
            print filename 

关于python - 找不到文件时如何继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238504/

相关文章:

python - 如何使用 pyqt 编写诺基亚应用程序?

python - 如何理解tensorflow错误消息?

python - 动态显示/隐藏QTextEdit的一部分

Python Beautiful soup 在html中插入注释

python - 从 Django 单元测试中获取通过或失败的输出

python - Celery+RabbitMQ 上任务进度未更新最新状态

python - Mersenne Twister 在 Python 中的开源实现?

python - 如何将文本左对齐?

python - 如何避免使用 sqlplus 的 Python Popen communications() 函数多次返回相同的 header

python - spider 4 中的绝地支持