471,330 Members | 1,783 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

CSV: list index out of range error

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
1 4561
bvdet
2,851 Expert Mod 2GB
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.

Similar topics

11 posts views Thread by Dave [Hawk-Systems] | last post: by
1 post views Thread by tkpmep | last post: by
22 posts views Thread by fniles | last post: by
10 posts views Thread by CarpeSkium | last post: by
6 posts views Thread by Shawn Minisall | last post: by
2 posts views Thread by Georgy Panterov | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.