Python 2.7:如何从异常对象中提取文件名

时间:2014-01-30 04:39:47

标签: python exception object python-2.7 filenames

参考traceback documentation,它说

  

请注意,文件名可用作例外的filename属性   宾语。

但是当我尝试使用代码调用错误对象时:

 errorIndex = fileList.index(os.error.filename)

它给了我错误:

ValueError: <member 'filename' of 'exceptions.EnvironmentError' objects> is not in list

我正在使用python 2.7。谁能解释这个错误以及我做错了什么?

编辑(完整代码):

def readFile(path, im_format, number_of_loops): 
fileList = sorted(os.listdir(path))
try:
    for file in fileList: #sorted function ensures files are read in ascending order
        if file.endswith(im_format):
            image_array = mahotas.imread(file)
            T = mahotas.thresholding.otsu(image_array)
            image = image_array>T
            image = img_as_ubyte(image)
            mahotas.imsave('C:/users/imgs/new/im_%00005d.tiff'%counter, image.astype(np.uint8))
except :
    errorIndex = fileList.index(os.error.filename)
    image_array1 = mahotas.imread(os.path.join(os.path.expanduser('~'),'imgs',fileList[errorIndex-1]))
    T = mahotas.thresholding.otsu(image_array1)

    image1 = image_array1>T


    image_array2 = mahotas.imread(os.path.join(os.path.expanduser('~'),'imgs',fileList[errorIndex+1]))
    T = mahotas.thresholding.otsu(image_array2)

    image2 = image_array2>T


    average = [(x+y)/2 for x,y in zip(image1,image2)]
    mahotas.imsave('C:/users/average.tiff'%counter, average.astype(np.uint8))
    fileList[errorIndex] = ('C:/users/imgs/average.tiff'%counter)

1 个答案:

答案 0 :(得分:0)

filename属性将位于异常的特定实例上。你需要这样的东西:

except os.error as e:
    errorIndex = fileList.index(e.filename)

正如目前所写,你的代码让我感到紧张。你似乎在except块中有很多代码。通常,您希望在except块中执行的操作是处理您尝试处理的特定错误所需的最小值。出于同样的原因,您的try块很大,这意味着可能会发生许多不同的错误。您通常应该使try块尽可能小,以便您只尝试处理一组经过严格限制的可能错误。

如果要捕获IOError,则需要使用except IOError as e来编写它。您可以使用except (IOError, OSError) as e来捕获任何一种错误。