By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,198 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

CSV: list index out of range error

P: 12
How do I check if a certain column exists in the CSV file, from the following code I try to check if s[8] exists. It gives me an error INDEX ERROR: List index out of range. If its Null I expect it to print NO rather than give me an error


Expand|Select|Wrap|Line Numbers
  1. f = open('C:\\Documents and Settings\\adesai\\Desktop\\save_lines.csv','r')
  2.  
  3.         while f:
  4.             line = f.readline()
  5.             if not line:
  6.                 break
  7.  
  8.             s = line.split(',')
  9.  
  10.  
  11.             if s[8]:
  12.                     print "YES"
  13.             else:
  14.                     print "NO"        
Nov 21 '07 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
How do I check if a certain column exists in the CSV file, from the following code I try to check if s[8] exists. It gives me an error INDEX ERROR: List index out of range. If its Null I expect it to print NO rather than give me an error


Expand|Select|Wrap|Line Numbers
  1. f = open('C:\\Documents and Settings\\adesai\\Desktop\\save_lines.csv','r')
  2.  
  3.         while f:
  4.             line = f.readline()
  5.             if not line:
  6.                 break
  7.  
  8.             s = line.split(',')
  9.  
  10.  
  11.             if s[8]:
  12.                     print "YES"
  13.             else:
  14.                     print "NO"        
To avoid the IndexError exception, you can check for s[8] in a try/except block:
Expand|Select|Wrap|Line Numbers
  1. try:
  2.     if s[8]:
  3.         print "Yes"
  4. except IndexError, e:
  5.     print "No"
Nov 22 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.