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
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')
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!")
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.
def creating_folder_for_csv_files(cwd):
try:
os.makedirs(cwd+'\\migration_data\\trade')
except os.error, e:
print "Could not create the destination folder for CSV files"
# end of first try/except block
try:
os.makedirs(cwd+'\\migration_data\\voucher')
except os.error, e:
print "Could not create the destination folder for CSV files"
In my code, the first try/except block works but the second does not. What's the problem?
The voucher might already exist.
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