简体   繁体   中英

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. 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. 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. Generally all you want to do in an except block is the minimum necessary to handle the specific error you're trying to handle. By the same token, your try block is large, meaning that many different errors could occur in it. 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.

If you want to catch an IOError, you need to write that, using except IOError as e . You can use except (IOError, OSError) as e to catch either kind of error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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