With the command next(a_file), I can skip the first line of a file but only if there is actually a line. If there is nothing in the file at the time of the command I get an error. How can I avoid this problem?
Example for error:
a_file = open("helloo.txt")
next(a_file)
print(a_file.read())
Just use a try: except block. You want to catch only the StopIteration exception, so that any other (FileNotFoundError,...) doesn't get caught here:
a_file = open("helloo.txt")
try:
next(a_file)
except StopIteration:
print("Empty file")
# or just
#pass
print(a_file.read())
You could wrap it with a try except block:
try:
next(a_file)
except StopIteration:
# handle the exception
You can simply make use of try-except block in python in order to detect if there is any error occurring while calling the next() method. In case any error occurs, which in your case will be StopIteration, we execute the except block and thus the program continues smoothly.
a_file = open("helloo.txt")
try:
next(a_file)
except StopIteration:
print("File is empty.")
print(a_file.read())
Check if the file is empty and if not, do next():
import os
a_file = open("helloo.txt")
if os.stat("helloo.txt").st_size != 0:
next(a_file)
print(a_file.read())
a_file.close()
Or you can use try except like this:
a_file = open("helloo.txt")
try:
next(a_file)
except StopIteration:
pass
print(a_file.read())
It is a bad practice to assign a open call to a variable via the = operator. Instead, use with:
with open("usernames.txt") as a_file:
try:
next(a_file)
print(a_file.read())
except StopIteration:
print("Empty")
I'd also like to introduce you to the finally statement; it only comes after both try and except are used in a block:
with open("usernames.txt") as a_file:
try:
next(a_file)
print(a_file.read())
except StopIteration:
print("Empty")
finally:
print("End!")
Related
Suppose I want to introduce a try-except block while handling a txt file. Which of the two following way of capturing the possible exception is correct?
try:
h = open(filename)
except:
h.close()
print('Could not read file')
try:
h = open(filename)
except:
print('Could not read file')
In other words, should the h.close() be called even if the exception occurs or not?
Secondly, suppose that you have the following code
try:
h = open(filename)
"code line here1"
"code line here2"
except:
h.close()
print('Could not read file')
If an error occurs in "code line here1", should I use h.close() in the except block?
Is there a difference with the previous coding lines?
You should use with, it will close the file appropriately:
with open(filename) as h:
#
# do whatever you need...
#
# when you get here, the file will be closed automatically.
You can enclose that in a try/except block if needed. The file will always be properly closed:
try:
with open(filename) as h:
#
# do whatever you need...
#
except FileNotFoundError:
print('file not found')
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
For instance, I have a function like:
def example():
fp = open('example.txt','w+')
fp.write(str(1/0))
fp.close()
Then it will throw an exception because 1/0 is not defined. However, I can neither remove example.txt nor modify example.txt. But I have some important data in Python, so that I can't simply kill Python and run it again.
How could I finish opening the file when the function finish with an exception.
What shall we do if we didn't place a try:.. except:.. ?
with open('example.txt','w+') as fp:
try:
fp.write(...)
except ZeroDivisionError as e:
print('there was an error: {}'.format(e))
Using the with context manager any files opened by it will be closed automatically once they go out of scope.
You can wrap that in a try/except to handle the error and close the file reader before the program ends.
def example():
fp = open('example.txt', 'w+')
try:
fp.write(str(1/0))
except ZeroDivisionError:
fp.close()
fp.close()
Edit: The answer by #IanAuld is better than mine. It would be best to accept that one.
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.
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.