简体   繁体   中英

Python: Try, Continue, Except statement in for loop

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM