If the code in the except
block runs it is because an exception was raised. You swallow the exception which makes it hard to know what's going wrong.
Your error message suggests that you are attempting to trap errors raised in the file open. But since your try
block surrounds the entire processing of the file, exceptions raised in the processing, as opposed to the file open, will be mis-reported as "Could not open file". If you really must handle the exception then you need to move the for
loop to be after the except
block.
Personally I'd be inclined to simply ignore the exception and let the default handling of the exception halt execution:
with open('sample.txt','r') as file:
for line in file:
(some action here)
If you must handle the exception then be discerning about the class exception that you handle. For example, handle just IOError
since that is what open
raises in case of failure.
try:
with open('sample.txt','r') as file:
for line in file:
(some action here)
except IOError:
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)