Catching Python exceptions using 'expect' method? - python

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

Related

Use try and except to skip a file

I am defining a list of nc files between 2 dates:
inlist = ['20180101.nc’, ‘20180102.nc’, ‘20180103.nc’]
Let’s suppose that the file in the middle (‘20180102.nc’) does not exist.
I am trying to use an exception and skip it and continue with the rest, but I can’t manage.
Here’s my code. Note that ncread(i)[0] is a function that reads one variable, which is then concatenated in xap:
xap = np.empty([0])
try:
for i in inlist:
xap=np.concatenate((xap,ncread(i)[0]))
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
continue
This code always stops when it tries to read the file that does not exist (‘20180102.nc’).
How can I skip this file and continue concatenating only the files that exist?
Thanks in advance.
Your try/except is placed on the wrong level, you want to try the read, and when it fails continue the loop. This means the try/except must be inside the loop:
xap = np.empty([0])
for i in inlist:
try:
xap=np.concatenate((xap,ncread(i)[0]))
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
continue
if you also consider another way, here is a simple way to reach your purpose.
use this to operate the system
import os
list all your file in current directory(you should change to your object path)
filelist=os.listdir("./")
inlist = ['20180101.nc', '20180102.nc', '20180103.nc']
xap = np.empty([0])
for i in inlist:
##** only read the "i" in filelist**
if i in filelist: xap=np.concatenate((xap,ncread(i)[0]))
You need to change IOError to FileNotFoundError:
xap = np.empty([0])
try:
for i in inlist:
xap=np.concatenate((xap,ncread(i)[0]))
except FileNotFoundError as e:
print "FileNotFoundError({0}): {1}".format(e.errno, e.strerror)
continue

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.

Save results to a txt file python

I want to save these email results to my results.txt file in the directory.
def parseAddress():
try:
website = urllib2.urlopen(getAddress())
html = website.read()
addys = re.findall('''[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?''', html, flags=re.IGNORECASE)
print addys
except urllib2.HTTPError, err:
print "Cannot retrieve URL: HTTP Error Code: ", err.code
except urllib2.URLError, err:
print "Cannot retrive URL: " + err.reason[1]
# need to write the addys data to results.txt
with open('results.txt', 'w') as f:
result_line = f.writelines(addys)
Use return addys at the end of your function. print will only output to your screen.
In order to retrieve addys, you would need to call the function in your with statement or create a variable that contains the result of parseAddress().
You can save the memory that a variable would use by simply calling the function, like so:
with open('results.txt', 'w') as f:
f.write ( parseAddress() )
You mistakenly indented the "with" statement one space. This makes it subjective to an earlier block. I would think any self-respecting Python interpreter would flag this as not matching any earlier indentation, but it seems to be fouling your output.
Also, please consider adding some tracing print statements to see where your code did execute. That output alone can often show you the problem, or lead us to it. You should always provide actual output for us, rather than just a general description.
You need to fix your indentation, which is important in Python as it is the only way to define a block of code.
You also have too many statements in your try block.
def parseAddress():
website = None
try:
website = urllib2.urlopen(getAddress())
except urllib2.HTTPError, err:
print "Cannot retrieve URL: HTTP Error Code: ", err.code
except urllib2.URLError, err:
print "Cannot retrive URL: " + err.reason[1]
if website is not None:
html = website.read()
addys = re.findall('''[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?''', html, flags=re.IGNORECASE)
print addys
# need to write the addys data to results.txt
with open('results.txt', 'w') as f:
result_line = f.writelines(addys)

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.

Python: Error message parsing

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))

Categories