Search code examples
pythontry-except

try/ except not handling multiple file paths


I wish to return a list of file names in a directory. The code should be able to work in 2 separate paths (for 2 separate users).

try:
    file_directory = "C:\\Users1\\Directory"
except: 
    file_directory = "C:\\Users2\\Directory"
files = os.listdir(file_directory)

But this returns

----> 5 files = os.listdir(file_directory)
    FileNotFoundError: [WinError 3] The system cannot find the path 
    specified: 'C:\\Users1\\Directory'

The code does work in both paths, (i.e. when Users1 is indeed the file path), or Users1 and 2 are swapped (i.e. when Users2 is the file path).

So why does the try/ except block not handle the error here?


Solution

  • The try block's code is executed first when the try/except block is used. The except block's code is executed instead in the event of an error. In this instance, the code in the try block is attempting to give the variable file_directory the value "C:Users1Directory." However, the except block's code will not be executed and an error will be thrown if the path "C:Users1Directory" does not exist.

    Before attempting to assign the path to the variable, you should use the os.path.exists() method to resolve this issue. You can then assign the alternative path to the variable if the first path does not exist. An illustration of this is as follows:

    if os.path.exists("C:\\Users1\\Directory"):
        file_directory = "C:\\Users1\\Directory"
    else:
        file_directory = "C:\\Users2\\Directory"
    files = os.listdir(file_directory)