With the following data, using the code snippet, I am getting the following error. Can you please help me with this. I am a beginner in python. Data :
"Id","Title","Body","Tags"
"Id1","Tit,le1","Body1","Ta,gs1"
"Id","Title","Body","Ta,2gs"
Code:
#!/usr/bin/python
import csv,sys
if len(sys.argv) <> 3:
print >>sys.stderr, 'Wrong number of arguments. This tool will print first n records from a comma separated CSV file.'
print >>sys.stderr, 'Usage:'
print >>sys.stderr, ' python', sys.argv[0], '<file> <number-of-lines>'
sys.exit(1)
fileName = sys.argv[1]
n = int(sys.argv[2])
i = 0
out = csv.writer(sys.stdout, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
ret = []
def read_csv(file_path, has_header = True):
with open(file_path) as f:
if has_header: f.readline()
data = []
for line in f:
line = line.strip().split("\",\"")
data.append([x for x in line])
return data
ret = read_csv(fileName)
target = []
train = []
target = [x[2] for x in ret]
train = [x[1] for x in ret]
Error:
target = [x[2] for x in ret]
IndexError: list index out of range
['']it gives you this error? Adding an if statement to check for that before appending your data would help?