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.
__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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With