Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a *type* of file exists in Python

Tags:

python

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.

like image 402
user1239183 Avatar asked Feb 29 '12 01:02

user1239183


People also ask

What is __ file __ in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.

How do I check if multiple files exist in Python?

To check if a file or folder exists we can use the path. exists() function which accepts the path to the file or directory as an argument. It returns a boolean based on the existence of the path. As you can see, it returns True when testing with the testfile.


1 Answers

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.

like image 124
Greg Hewgill Avatar answered Sep 29 '22 10:09

Greg Hewgill