I realize this looks similar to other questions about checking if a file exists, but it is different. I\'m trying to figure out how to check that a type of
Look at the glob module:
import glob
import os
import sys
databases = filter(os.path.isfile, glob.glob('./*.fna'))
if not databases:
sys.stderr.write("No database found.\n\n")
exit(1)
for database in databases:
do_something_with(database)
filenames = os.listdir(os.curdir)
found = False
for filename in filenames:
if os.path.isfile(filename) and filename.endswith('.fna'):
found = True
if not found:
sys.stderr.write ('No database file found. Exiting program. \n')
sys.exit(-1)
The for statement in Python has a little-known else
clause:
for filename in filenames:
if os.path.isfile(filename) and filename.endswith(".fna"):
# do stuff
break
else:
sys.stderr.write ('No database file found. Exiting program. \n')
sys.exit(-1)
The else
clause is run only if the for
statement runs through its whole enumeration without executing the break
inside the loop.
If you are using exceptions, do not test to see if the file exists. That's why you're using exceptions to start with.
try:
# No if statement doing the check
# Start doing stuff assuming abc.fna exists
except:
# Uh oh! Something went bad.
# Display error messages, clean up, carry on
To clarify, consider the code snippet:
try:
with open('hi.txt') as f:
print f.readlines()
except:
print 'There is no hi.txt!'
Your try
/except
block didn't work because os.path.isfile
does not throw an exception if it fails; it merely returns False
.
else
clauses for for
loops are weird and non-intuitive. Using break
to signify that the loop was successful rather than legitimately breaking it is just weird, and contrary to Python's philosophy.
Here's a nice, Pythonic way of doing what you want:
want = lambda f: os.path.isfile(f) and f.endswith(".fna")
valid_files = [f for f in os.listdir(os.curdir) if want(f)]
if len(valid_files) == 0:
print >>sys.stderr, "failed to find .fna files!"
sys.exit(1)
for filename in valid_files:
# do stuff
Check out os.path.splitext(path) function which says:
Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').
Here's an example:
>>> os.path.splitext("./01The News from Lake Wobegon/AlbumArtSmall.jpg")
('./01The News from Lake Wobegon/AlbumArtSmall', '.jpg')
>>>