简体   繁体   English

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

[英]Python 2.7: How to extract filename from exception object

Referring to the traceback documentation , it says 参考回溯文档 ,它说

Note that the filename is available as the filename attribute of the exception object. 请注意,文件名可用作异常对象的文件名属性。

But when I try to call the error object using the code: 但是,当我尝试使用代码调用错误对象时:

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

it gives me the error: 它给了我错误:

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

I am using python 2.7. 我正在使用python 2.7。 Can anyone explain this error and what I am doing wrong? 谁能解释这个错误以及我在做什么错?

Edit (Full Code): 编辑(完整代码):

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)

The filename attribute will be on a specific instance of an exception. filename属性将位于异常的特定实例上。 You need something like: 您需要类似:

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

As currently written your code makes me nervous. 就目前而言,您的代码使我感到紧张。 You seem to have a lot of code inside an except block. 您似乎在except块内有很多代码。 Generally all you want to do in an except block is the minimum necessary to handle the specific error you're trying to handle. 通常,您要在except块中要做的就是处理您要处理的特定错误的最低要求。 By the same token, your try block is large, meaning that many different errors could occur in it. 同样,您的try块很大,这意味着其中可能发生许多不同的错误。 You should generally make the try block as small as possible, so that you only attempt to handle a carefully limited set of possible errors. 通常,您应该使try块尽可能小,以便仅尝试处理小心限制的一组可能的错误。

If you want to catch an IOError, you need to write that, using except IOError as e . 如果要捕获IOError,则需要使用except IOError as e进行编写。 You can use except (IOError, OSError) as e to catch either kind of error. 您可以将except (IOError, OSError) as e来捕获任何一种错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM