0

I literally just learned about the concept of working around errors encountered in for-loops. I have a list of files read in from my local computer and I'd like to read them in as pandas dataframes.

Let's say I have a list of files and each file as columns "A", "B" and "C". If there is a specific column, lets say column "B" from file3.tbl, missing from a file on my computer, I want to continue with my for loop.

list = ['file1.tbl', 'file2.tbl', 'file3.tbl']
for i in range(len(list)):
    data = pandas.read_csv(list[i])
    try:
        b = data['B']
        continue
    except Exception:
        print "Column B not included in file: ", list[i]

This seems to work somewhat but it prints the except statment len(list) number of times, like so:

Column B not included in file: file3.tbl
Column B not included in file: file3.tbl
Column B not included in file: file3.tbl

Is there a way to get it to print only one time for that specific iteration?

6
  • Do you mean list[i] instead of list[ii]? Also, the indentation is off on your try block. Commented Sep 20, 2017 at 3:44
  • Yes, I do! I'll edit both of those. Commented Sep 20, 2017 at 3:48
  • 5
    Don’t do except Exception; it has the potential to hide a bunch of things you would rather know about. except KeyError would be more specific. Also, are you sure this is actually your code? It’s strange for .dat to be printed when your list only contains .tbl. Commented Sep 20, 2017 at 3:52
  • 1
    A couple style pointers: don't use builtin names (such as list) for your variables. Use a meaningful name such as files or filenames. Also, it's better to loop over the items in such a list directly with for file in files: instead of looping over the list indexes. Commented Sep 20, 2017 at 4:08
  • I think @Ryan nailed it -- your error message refers to file3.dat, but your code defines file3.tbl. This isn't the actual code you're running. Commented Sep 20, 2017 at 4:20

1 Answer 1

2

As hinted in the comments, you likely have namespace issue. Here's some cleaned up code that should print uniquely for each Exception. It includes the Pythonic suggestions that agree with the comments.

For three csv-like files "file1.tbl", "file2.tbl", "file3.tbl", I get the following:

import pandas as pd


filenames = ["file1.tbl", "file2.tbl", "file3.tbl"]        # @John Gordon
for fn in filenames:
    data = pd.read_csv(fn)
    try: 
        b = data['B']
    except (KeyError):                                     # @Ryan
        print("Column B not included in file: ", fn)
    else:
        # Do something with b (optional)
        pass


# Column B not included in file:  file1.tbl
# Column B not included in file:  file2.tbl
# Column B not included in file:  file3.tbl
Sign up to request clarification or add additional context in comments.

5 Comments

Hi pylang, thanks for nicely summing up the suggestions. Would the else statement continue the except part of the logic or would it pick up where the try statement left off? Or would it start at the beginning of the loop?
@DaxFeliz: The else statement will be executed only if no exceptions occur.
It continues from the try block in the absence of an exception, as @Arun mentioned.
Logically, this makes sense to me but this version still prints the except message multiple times.
I ran the code on .tbl files (?) and get the results in the updated post. Try a fresh Python session. Then try new files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.