Cayman
Cayman

Reputation: 3

Cannot use next() on csv-read itererator

I am creating a small programm to sort a csv-list. Unfortunately, I am not able to use the next() method to skip over a line. I keep getting the error:

File "file.py", line 106, in detail_sorter next(line) TypeError: 'list' object is not an iterator

However, I am iterating through a csv-file, so I don't understand why it keeps thinking it is a list?

    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)

Upvotes: 0

Views: 286

Answers (2)

TomMP
TomMP

Reputation: 815

You are calling next() on line, instead of creader. line, in this case, is of type list.

From the code you provided, I assume you want to just continue with the next line if colA == ''. What you are looking for, is the continue keyword. This tells python to skip any code below and continue with the next iteration within a loop.

However, that would only make sense if more code follows within the loop. Otherwise, it will just go to the next element in the loop either way.

Upvotes: 1

Dolfa
Dolfa

Reputation: 792

I think that next(line) is unnecessary. You are already iterating through 'csvreader' (which is iterator) in line: "for line in creader:".

I am guessing you want to continue, or skip a line if line is empty. You can use just 'continue' instead of 'next(line)'.

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

Upvotes: 1

Related Questions