UPDATE: I think I may have just realized what I need to figure out re: the below, which is the correct error type to specify with the except clause (new to this, obviously)
Starting in a specified root directory, my program iterates through subdirectories, then files within those, identifying valid (.csv) data files and then aggregating and performing calculations on the data.
In cases where the root directory happens to be empty, can someone suggest a clean/graceful way to simply exit the program at the start without further processing?
I tried to adapt a suggestion I found here, but it didn't work as I expected:
Exit gracefully if file doesn't exist
That person's code was:
file = open('file.txt', 'r')
print('There was an error opening the file!')
dir = os.listdir(masterDirPath)
item = dir
print('The data area is empty.')
To exit your program immediately you should use either
quit(). Instead of throwing an error you could use the fact that many objects in Python are truthy; an empty list is
False, and a list with one or more elements is
import os dir_contents = os.listdir('.') if dir_contents: do_stuff else: print('Directory was empty. Exiting') exit()
If you prefer explicitness to implicitness you could also check the length of your list using
len(dir_contents) before indexing into it.
You might also want to avoid using
dir in Python as a variable name as it will shadow the builtin function