gpt4 book ai didi

python - CsvReader 下一个函数

转载 作者:太空狗 更新时间:2023-10-29 20:33:33 26 4
gpt4 key购买 nike

我得到了一个 csv 文件,但我想跳过第一行数据并转到下一行。这是我的代码:

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)

如您所见,我将 csv 文件作为列表返回,然后将其传递给 generate_xml 函数。然而,当我运行完整的程序时,有一个

error: 'list' object has no attribute 'next'

最佳答案

您有一个列表,而不是迭代器。只需切片即可:

for row in reader[1:]:

或者当你还有一个实际的 csv.reader() 对象时跳过第一行:

def read_csv(inputfile):
reader = csv.reader(inputfile)
next(reader)
return list(reader)

最好返回 reader 对象,而不是将所有行读入内存;除非您绝对需要随机访问行。

您还应该真正使用 next() function相反,因为它适用于 Python 2.6+ 和 3,其中迭代器 .next() 方法已重命名为 .__next__()

否则你永远不会使用for row in reader.next(),因为.next()csv .reader() 迭代器返回 一个 行。

关于python - CsvReader 下一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17513438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com