with open(file) in except - python

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.

Related

Python:The process cannot access the file because it is being used by another process

try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
Here I want to read something in a .txt file and then erase content and delete it. But it always shows it cannot delete it as 'The process cannot access the file because it is being used by another process'.
Actually what I need is to delete the .txt file, but it cannot delete immediately sometimes, so I erase the content at first in case that it will be read again. So is there any good way to read something in a .txt file and then delete this file as soon and stable as possible?
You should NOT call f.close() nor g.close(). It is called automatically by with statement.
remove the unnecessary close() statements to start - like #grapes mentioned - why are you truncating what you are deleting? just delete it...
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
exec(s)
except Error as e:
print(e)
else:
os.remove(masterpath)
FYI, it is bad form to execute the contents of a file if you do not control the contents of said file.
another option:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
try:
s = f.read()
except Error as e:
print(e)
else:
exec(s)
os.remove(masterpath)
Try to use short sleep in exception part:
try:
masterpath = os.path.join(path, "master.txt")
with open(masterpath, 'r') as f:
s = f.read()
f.close()
exec(s)
with open(masterpath, 'w') as g:
g.truncate()
g.close()
os.remove(masterpath)
except WindowsError:
time.sleep(sleep)
else:
break
Another way is to use:
os.remove(masterpath)

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)

try...except...else v nested try...except

Why is else clause needed for try statement in python ?
Taking it forward:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
It occurs to me that the corner case solved by else clause still can be avoided by a nested try...except avoiding the need of else? :
try:
f = open('foo', 'r')
try:
data = f.read()
f.close()
except:
pass
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
try..except..else may not be needed, but it can be nice. In this case, the try..except..else form is distinctly nicer, in my opinion.
Just because you can do without an element of syntax, doesn't make it useless. Decorator syntax is purely syntax sugar (the most obvious example, I think), for loops are just glorified while loops, et cetera. There's a good place for try..except..else and I would say this is one such place.
Besides, those two blocks of code are far from equivalent. If f.read() raises an exception (disk read error, data corruption inside the file or some other such problem), the first will raise an exception as it should but the second will lose it and think that everything has worked. For myself, I would prefer something more along these lines, which is shorter and still easier to understand:
try:
with open('foo', 'r') as f:
data = f.read()
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
(This assumes that you want to catch errors in file.read and file.close. And I can't really see why you wouldn't.)
Actually, is not always needed you can simply do:
f = None
try:
f = open('foo', 'r')
except IOError:
error_log.write('Unable to open foo\n')
if f:
data = f.read()
f.close()

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