Catching a specific IO error

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Apr 24 08:02:49 EDT 2007


En Tue, 24 Apr 2007 08:44:05 -0300, Tina I <tinaweb at bestemselv.com>  
escribió:

> Hi group :)
>
> I have this standard line:
>
> 	export = open(self.exportFileName , 'w')
>
> 'exportFileName' is a full path given by the user. If the user gives an  
> illegal path or filename the following exception is raised:
> "IOError: [Errno 2] No such file or directory: /some/path/file.txt"
>
> So at the moment I do this:
>
> 	try:
> 		export = open(self.exportFileName , 'w')
> 		export.write("Something")
> 		export.close()
> 	except IOError:
> 		# calling an error handling method.
>
> Now, this works but of course it catches every IOError, and I can not  
> figure out how to restrict it to only catch the "[Errno 2]"?

You can get the 2 as the errno exception attribute. BTW, 2 == errno.ENOENT

  	try:
  		export = open(self.exportFileName , 'w')
  	except IOError, e:
		if e.errno==errno.ENOENT:
			# handle the "No such file or directory" error
  		# calling an error handling method.

See http://docs.python.org/lib/module-exceptions.html

-- 
Gabriel Genellina



More information about the Python-list mailing list