[英]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.