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?
list[i]instead oflist[ii]? Also, the indentation is off on yourtryblock.except Exception; it has the potential to hide a bunch of things you would rather know about.except KeyErrorwould be more specific. Also, are you sure this is actually your code? It’s strange for.datto be printed when your list only contains.tbl.list) for your variables. Use a meaningful name such asfilesorfilenames. Also, it's better to loop over the items in such a list directly withfor file in files:instead of looping over the list indexes.file3.dat, but your code definesfile3.tbl. This isn't the actual code you're running.