i am given a csv file but i want to skip the first row of data and move on to the next. Here is my code:
def read_csv(inputfile):
return list(csv.reader(inputfile)) #<-----
def generate_xml(reader,outfile):
root = Element('Solution')
root.set('version','1.0')
tree = ElementTree(root)
head = SubElement(root, 'DrillHoles')
description = SubElement(head,'description')
current_group = None
i = 1
for row in reader.next(): #<-----
x1,y1,z1,x2,y2,z2,cost = row
if current_group is None or i != current_group.text:
current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})
collar = SubElement(current_group,'collar')
toe = SubElement(current_group,'toe')
cost1 = SubElement(current_group,'cost')
collar.text = ','.join((x1,y1,z1))
toe.text = ','.join((x2,y2,z2))
cost1.text = cost
i+=1
head.set('total_holes', '%s'%i)
indent.indent(root)
tree.write(outfile)
As you can see, i return the csv file as a list then i pass it onto the generate_xml function. However when i run the complete program there is an
error: 'list' object has no attribute 'next'
next() will obtain the next value as it iterates through the file. In the below code the for loop is calling . next() on the iterator each time and allocating the result of next to the variable row.
The reader itself doesn't manage any resources that would need to be cleaned up when you're done using it, so there's no need to close it; it'd be a meaningless operation.
Example 1: Read CSV files with csv. reader() is used to read the file, which returns an iterable reader object. The reader object is then iterated using a for loop to print the contents of each row.
For python 2.x, the code is:
data = []
with open('xxx.csv') as f:
r = csv.reader(f)
name = r.next()[1] # assume the first 2 rows are name and unit
unit = r.next()
for row in r:
data.append(row)
For python 3.x, use next(r)
instead of r.next()
You have a list, not an iterator. Just slice it instead:
for row in reader[1:]:
or skip that first row when you still have an actual csv.reader()
object:
def read_csv(inputfile):
reader = csv.reader(inputfile)
next(reader)
return list(reader)
You'd be better off returning the reader
object instead of reading all rows into memory there; unless you absolutely need random access to the rows.
You also should really use the next()
function instead as it works for Python 2.6+ and 3, where the iterator .next()
method has been renamed to .__next__()
.
You'd otherwise never use for row in reader.next()
, because .next()
on a csv.reader()
iterator returns one row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With