Search code examples
pythontry-except

How to use multiple exceptions conditions properly?


I am working with many files and this is an example of a smaller portion. Imagine I have my file names inside a list like this:

filelist = ["file1.csv", "file2.csv", "file3.csv"]

I would like to import them as a dataframe. If I am not able to do this condition, I would try another way... and if I still don't get it, I would like to add this filename to another list (errorfiles).

errorfiles = []
for file in filelist:
    try:
        df = pd.read_csv(file)
    except:
        df = pd.read_csv(file + ".csv")
    else:
        errorfiles.append(file)

I tried this code above, but it raises the following error and don't add the file names with error to my list:

FileNotFoundError: [Errno 2] No such file or directory: 'file1.csv.csv'

I think I am not doing this try-except correctly. In this example, all these files should be in errorfiles as I can't import them. Anyone could help me?


Solution

  • You need a nested try/except for the case where the second file is not found.

    errorfiles = []
    for file in filelist:
        try:
            df = pd.read_csv(file)
        except FileNotFoundError:
            try:
                df = pd.read_csv(file + ".csv")
            except FileNotFoundError:
                errorfiles.append(file)