簡體   English   中英

Python 2.7:如何從異常對象中提取文件名

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

參考回溯文檔 ,它說

請注意,文件名可用作異常對象的文件名屬性。

但是,當我嘗試使用代碼調用錯誤對象時:

 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)

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來捕獲任何一種錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM