使用try和except跳过fi

2024-03-28 08:02:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在定义两个日期之间的nc文件列表:

inlist = ['20180101.nc’, ‘20180102.nc’,  ‘20180103.nc’]

假设中间的文件('20180102.nc')不存在。你知道吗

我正在尝试使用一个异常并跳过它,然后继续使用其余的异常,但我无法管理。你知道吗

这是我的密码。请注意,ncread(i)[0]是一个函数,它读取一个变量,然后在xap中串联:

xap = np.empty([0])
try:
    for i in inlist:
        xap=np.concatenate((xap,ncread(i)[0]))
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
    continue

当试图读取不存在的文件('20180102.nc')时,此代码总是停止。你知道吗

如何跳过此文件并继续仅连接存在的文件?你知道吗

提前谢谢。你知道吗


Tags: 文件函数in密码列表for定义np
3条回答

try/except放在错误的级别上,您想尝试读取,当失败时继续循环。这意味着try/except必须在循环中:

xap = np.empty([0])
for i in inlist:
    try:
        xap=np.concatenate((xap,ncread(i)[0]))
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
        continue

您需要将IOError更改为FileNotFoundError

xap = np.empty([0])
try:
    for i in inlist:
        xap=np.concatenate((xap,ncread(i)[0]))
except FileNotFoundError as e:
    print "FileNotFoundError({0}): {1}".format(e.errno, e.strerror)
    continue

如果你也考虑另一种方法,这里有一个简单的方法来达到你的目的。你知道吗

使用此按钮操作系统

import os

列出当前目录中的所有文件(应更改为对象路径)

filelist=os.listdir("./")

inlist = ['20180101.nc', '20180102.nc',  '20180103.nc']
xap = np.empty([0])
for i in inlist:
   ##** only read the "i" in filelist** 
   if i in filelist: xap=np.concatenate((xap,ncread(i)[0]))

相关问题 更多 >