1

I am writing a python script that parses information from different files into pandas dataframes. At first, I am aiming at a certain directory, then I am calling the commands to parse the information from multiple files. If, however, that directory does not exist, I should execute the exact same code, though in another directory. To illustrate, it should be something like:

import os
try:
    cwd = "/path/do/dir"
    os.chdir(cwd)
    #do a code block here

except FileNotFoundError: # i.e. in case /path/to/dir does not exist
    cwd = /path/to/anotherDir
    os.chdir(cwd)
    # do the same code block

What I am doing currently is to repeat the same code block in the try and in the except chunks, though I was wondering if there is a more elegant way of doing it, like assigning the whole code block to a variable or a function, then calling this variable/ function in the except chunk.

BCArg
  • 2,094
  • 2
  • 19
  • 37
  • 1
    How about looping through with `for file in files:` and put a `try` and `except` inside the loop? – Jeremy H Aug 08 '19 at 15:01
  • What is it actually you are trying to achieve? This looking you are recursively trying to walk a directory tree; use `os.walk` for that instead. See https://stackoverflow.com/questions/6639394/what-is-the-python-way-to-walk-a-directory-tree Also, you should always try to keep the scope of your try / except blocks as minimal as possible: otherwise, an error in the except clause will still be thrown – martyn Aug 08 '19 at 15:02

2 Answers2

1

You can simply iterate over a list of paths, and try your code block for every file. You can even add a break at the end of your try block if you want to stop iterating as soon as you found a path that worked.

paths = ['path/to/dir', 'path/to/other/dir']

for cwd in paths:
    try:
        os.chdir(cwd)

        # code that may fail here

        break

    except FileNotFoundError:
        # This will NOT cause the code to fail; it's the same as `pass` but
        # more informative
        print("File not found:", cwd)
Right leg
  • 16,080
  • 7
  • 48
  • 81
0

Isn't it better to simply check if the directory/file exists?

import os
if os.path.isdir('some/path') and os.path.isfile('some/path/file.txt'):
    os.chdir('some/path')
else:
    os.chdir('other/path')

#code block here

Of course, this assumes that nothing else can go wrong in the '#code block'.

Thomas Hilger
  • 456
  • 3
  • 11