首页 > 解决方案 > 不能在 csv-read 迭代器上使用 next()

问题描述

我正在创建一个小程序来对 csv 列表进行排序。不幸的是,我无法使用 next() 方法跳过一行。我不断收到错误:

文件“file.py”,第 106 行,详细信息_sorter next(line) TypeError: 'list' object is not an iterator

但是,我正在遍历一个 csv 文件,所以我不明白为什么它一直认为它是一个列表?

    with open(filename+".csv","r+") as file:
        creader = csv.reader(file,delimiter=";")

        with open(filename+"_ex.csv","w+") as export:
            cwriter = csv.writer(export,delimiter=";")

            for line in creader:
                line_count = creader.line_num

                colA = line[0]
                colB = line[1]
                colC = line[2]
                colD = line[3]
                colE = line[4]
                colF = line[5]
                colG = line[6]
                colH = line[7]
                colI = line[8]

                if colA == '':
                     next(line)

标签: pythoncsv

解决方案


我认为 next(line) 是不必要的。您已经在行中迭代“csvreader”(即迭代器):“for line in creader:”。

我猜您想继续,或者如果行为空则跳过一行。您可以只使用“继续”而不是“下一个(行)”。

https://docs.python.org/3/tutorial/controlflow.html


推荐阅读