Spurious character in IOError exception

Peter Otten __peter__ at web.de
Thu Apr 28 11:24:03 CEST 2011


loial wrote:

> When I correctly trap an IOError a spurious u' appears in the file
> path in the exception message :
> 
> The path used in the code is correct i.e. /home/myfile
> 
> But the error message says :
> 
> [Errno 2] No such file or directory: u'/home/myfile'
> 
> 
> I am simply doing
> 
>  except IOError, e:
>             print str(e)
> 
> 
> Any ideas where the 'u  is coming from?
> 
> This is python 2.4.1

The filename does not appear directly in the error message, it is first 
converted by repr(). This ensures that

(1) the error message will consist only of ascii characters
(2) the filename can reliably reconstructed from the message

>>> try: open("äöü")
... except IOError, e: print e
...
[Errno 2] No such file or directory: '\xc3\xa4\xc3\xb6\xc3\xbc'

but the output may puzzle end users. The u'...' in your case means that you 
passed a unicode string to the open(...) function.

>>> try: open(u"äöü")
... except IOError, e: print e
...
[Errno 2] No such file or directory: u'\xe4\xf6\xfc'

If you are sure that the output device supports unicode output (i. e. has a 
known encoding and can display the characters in your filename) you can 
build a friendlier message

>>> try: open(u"äöü")
... except IOError, e: print u"[Errno %d] %s: %s" % (e.errno, e.strerror, 
e.filename)
...
[Errno 2] No such file or directory: äöü

Be aware though that some problems become near-impossible to detect that 
way:

>>> try: open(u"äöü\n") # note the trailing newline
... except IOError, e: print u"[Errno %d] %s: %s" % (e.errno, e.strerror, 
e.filename)
...
[Errno 2] No such file or directory: äöü

>>>





More information about the Python-list mailing list