0

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():
    try:
        file = open('file.txt', 'r')
    except IOError:
        print('There was an error opening the file!')
        return

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():
    try:
        item = dir[0]
    except IOError:
        print('The data area is empty.')
        return

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

Community
  • 1
  • 1
Margarita
  • 1,193
  • 2
  • 8
  • 12
  • You should check the length of the dir list, or add an except clause for the index error – OneCricketeer Nov 22 '16 at 14:22
  • Possible duplicate of [I want to exception handle 'list index out of range.'](http://stackoverflow.com/questions/11902458/i-want-to-exception-handle-list-index-out-of-range) – OneCricketeer Nov 22 '16 at 14:23

5 Answers5

1

An empty list has no elements so you should catch IndexError instead of IOError.

def main():
    try:
        item = dir[0]
    except IndexError:
        print('The data area is empty.')
        return
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

Why are you using an exception?

if not dir:
    print('The data area is empty')
    exit(0)

item = dir[0]
Sven
  • 2,839
  • 7
  • 33
  • 53
1

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

0
#!/usr/bin/env python

import os 
path = 'path-to-your-dir'
if os.listdir(path) == []: 
    exit(0)
else: 
    print "Your other code goes here."
r0xette
  • 898
  • 3
  • 11
  • 24
0

These are the exit commands and its definitions

exit(0) means a clean exit without any errors / problems

exit(1) means there was some issue / error / problem and that is why the program is exiting.

os._exit() for child processes

quit() the SystemExit exception behind the scenes.

sys.exit() kill the interpreter

Januka samaranyake
  • 2,385
  • 1
  • 28
  • 50