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
.