Python: Error message parsing - python

I'm trying to handle IOError generated when trying to open a non existent file. I do:
try:
inputFile = open('nosuchfile', 'r')
except IOError as exception:
print 'error: %s' % (exception)
This gives me:
error: [Errno 2] No such file or directory: 'nosuchfile'
But I'm only interested in the message and not the [Errno 2] part. So I change my code.
print 'error: %s' % (exception.strerror)
But now I get:
error: No such file or directory
Where did the name of the file go? I know I could just print the file name separately, but I would really like how (if at all) the name was stored in the exception, but not in either of its arguments (printing exception.errno gives 2).
I am using version 2.7.3.

The filename is stored in, well, the filename property:
try:
inputFile = open('nosuchfile', 'r')
except IOError as exception:
print ('error: %s: %r' % (exception.strerror, exception.filename))

Related

Python: FileNotFoundError not caught by try-except block

recently i started learning Python and encountered a problem i can`t find an answer to.
Idea of the program is to ask for username, load a dictionary from JSON file, and if the name is in the dictionary - print the users favourite number.
The code, that loads the JSON file looks like this:
import json
fav_numbers = {}
filename = 'numbers.JSON'
name = input('Hi, what`s your name? ')
try:
with open(filename) as f_obj:
fav_numbers = json.load(f_obj)
except FileNotFoundError:
pass
if name in fav_numbers.keys():
print('Hi {}, your fav number is {}, right?'.format(name, fav_numbers[name]))
else:
number = input('Hi {}, what`s your favourte number? '.format(name))
fav_numbers[name] = number
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, filename)
Still, as i try to run it, it crashes, telling me:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'numbers.JSON'
File "/home/niedzwiedx/Dokumenty/Python/ulubionejson.py", line 22, in <module>
with open(filename) as f_obj:
What i`m doing wrong to catch the exception? (Already tried changing the FileNotFoundError to OSError or IOError)
The error comes from you last line, outside of your try/except
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, filename)
filename is a string, not a file.
You have to use
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, f_obj)
For additional safety, you can surround this part with try/except too
try:
with open(filename, 'w') as f_obj:
json.dump(fav_numbers, f_obj)
except (FileNotFoundError, PremissionError):
print("Impossible to create JSON file to save data")

fake `.gz` raise IOError, 'Not a gzipped file'

Let's say I have a fake gz file test.bson.gz generated by echo "hello world" > test.bson.gz, and I have tried:
try:
bson_file = gzip.open('test.bson.gz', mode='rb')
except:
print("cannot open")
No exception will be caught here. (Really strange, since this is not a valid gz...)
Then I do:
data = bson_file.read(4)
I will get:
File "/usr/lib/python2.7/gzip.py", line 190, in _read_gzip_header
raise IOError, 'Not a gzipped file'
IOError: Not a gzipped file
Is there any way that I can determine (even catch error) whether this .gz is valid when I try to open it, not wait until I wanna read it?
Thanks!
You can use gzip.peek(n):
Read n uncompressed bytes without advancing the file position.
try:
bson_file = gzip.open('test.bson.gz', mode='rb')
bson_file.peek(1)
except OSError:
print("cannot open")
That way you will catch the error without consuming the file contents.
Hint: You should avoid catching all errors unconditionally. I added except OSError, because IOError was merged to OSError in Python 3.3 - see PEP3151.

Under which circumstances will the python f.readlines method fail?

I use the code below to read in a text file (always a few thousand lines long). Is the except Exception as e block unnecessary?
try:
in_file=open(in_file,'rU')
try:
in_content=in_file.readlines()
except Exception as e:
sys.stderr.write('Error: %s\n' % e.message)
sys.exit(1)
finally:
in_file.close()
except IOError:
sys.stderr.write('I/O Error: Input file not found.')
sys.exit(1)
Also please tell me of the circumstances under which the file.readlines() method in Python will fail?
I believe that IOError is the only possible thing that can happen. This covers both the file not existing and inadequate permissions. Any python reference I have seen only has IOError with files :). I'm not sure by what you mean with the stack trace, since it seems to just print the error itself?
import sys
try:
with open("in_file",'rU') as in_file:
in_content=in_file.readlines()
except Exception as e: #Should be replaceable with IOError, doesn't hurt to not
sys.stderr.write('%s\n' % e)
sys.exit(1)
The pythonic way to read file looks like this:
with open(in_file_name,'rU') as in_file:
in_content = in_file.readlines()
This should give you all the benefits of your code. So you don't need to worry about what kind of errors can occur. Python will take care of it. A file opened using the with statement will be closed in case of an exception.

with open(file) in except

In a try...except block i want to log the Exception error message to a file in the except path.
try:
doc = etree.parse(urllib2.urlopen(url))
except Exception, e:
print '%s: %s' % (e, url)
with open('error.txt', 'a') as f:
f.write('%s:%s\n' % url, e)
return
The print shows the error, but the with open ... f.write is not excecuted.
in the same script the relaxng validation is written to file
if not RELAXNG.validate(doc):
with open('error.txt', 'a') as f:
f.write('%s\n' % RELAXNG.error_log)
return
Can somebody explain to me, why
with open('myfile.txt', 'a') as f
f.write( ...
is posible in the if statement, but not in an except?
write() does not accept multiple arguments; you are probably missing parenthesis:
f.write('%s:%s\n' % (url, e))
Other than that, use absolute paths, not relative, as you can easily write the file in an unexpected place otherwise.
File operations inside except works fine.
>>> try:
raise SyntaxError("Hello")
except Exception:
with open("in.txt") as f:
print "F"
F
It should work. Try this for example:
try:
raise Exception
except Exception:
with open('error.txt', 'a') as f:
f.write('foobar')
If you run the above you will see foobar been written to file.
Is error.txt writeable by your process? There is some reason it's not writing to your file but it's not because the 'with' file context isn't allowed inside an except block.

Catching Python exceptions using 'expect' method?

import sys
try:
file = open("words.txt")
expect(IOError):
if file:
print "%s" % file
else:
print "Cant the %s file" % "words.txt"
this gives me an a error -
File "main.py", line 4
expect(IOError):
SyntaxError: invaild syntax
What im going wrong/ how do you fix this
Actually, it is except as in exception:
For instance:
except IOError:
print "Error opening file!"
I assume you are trying to handle exceptions. In that case, use except, not expect. In any case except is not a function, rather it precedes a block of error handling code. When using files, you may want to look at the with statement and try-except-finally. The correction to your code is-
import sys
try:
file = open("words.txt")
except IOError:
#Handle error
pass
if file:
print "%s" % file
else:
print "Cant the %s file" % "words.txt"
I hope this helps.
It's except. Read this.
I think you're looking for except. The error handling part of the python tutorial explains it well.
-John
>>> try:
... f = open('words.txt')
... except IOError:
... print "Cant the %s file" % "words.txt"
... else:
... print "%s" % f

Categories