Reputation: 111
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 file exists and exit if it doesn't. The code I tried originally is this:
filenames = os.listdir(os.curdir)
for filename in filenames:
if os.path.isfile(filename) and filename.endswith('.fna'):
##do stuff
This works to 'do stuff' to the file that ends in .fna, but I need it to check and make sure the .fna file is there and exit the program entirely if not.
I tried this:
try:
if os.path.isfile(filename) and filename.endswith('.fna'):
## Do stuff
except:
sys.stderr.write (‘No database file found. Exiting program. /n’)
sys.exit(-1)
But that didn't work, it just skips the whole function if the .fna file isn't there, without printing the error.
Upvotes: 11
Views: 11153
Reputation: 1
I also have a very similar code photo as you but mine is a code like is there an error or not. maybe you can find something useful
for belge in tarama:
try:
if belge.name.endswith('.docx') or belge.name.endswith('.doc'):
Document(belge)
elif belge.name.endswith('.pptx'):
Presentation(belge)
elif belge.name.endswith(".xlsx"):
pd.read_excel(belge)
elif belge.name.endswith(".pdf"):
pdfpath=os.path.abspath(belge)
PyPDF2.PdfReader(pdfpath)
elif belge.name.endswith(".jpg") or belge.name.endswith(".jpeg"):
jpgpath=os.path.abspath(belge)
matplotlib.image.imread(jpgpath)
else:
yenipath=os.path.abspath(belge)
tarama=os.scandir(yenipath)
func(tarama)
except :
print ("Dosya açılmıyor !",belge.name)
Upvotes: 0
Reputation: 77399
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)
Upvotes: 8
Reputation: 2972
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')
>>>
Upvotes: 0
Reputation: 50
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
Upvotes: 0
Reputation: 22679
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!'
Upvotes: 0
Reputation: 994787
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.
Upvotes: 12
Reputation: 198526
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)
Upvotes: 2