Margarita Margarita - 8 months ago 77
Python Question

Exit Python program if data directory is empty

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:

def main():
file = open('file.txt', 'r')
except IOError:
print('There was an error opening the file!')

I gave the above a try, and it works for the particular case above. However, when I tried to adapt it as follows, it 'broke' and I got an "Index out of range error", instead dropping down to the except code.

dir = os.listdir(masterDirPath)
def main():
item = dir[0]
except IOError:
print('The data area is empty.')

(Also/instead, I very much welcome suggestions for some completely other approach to the task overall)

Answer Source

To exit your program immediately you should use either exit() or 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 True.

import os
dir_contents = os.listdir('.')
if dir_contents:
    print('Directory was empty. Exiting')

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 dir().