0

In my code there is a function contains a csv reader like following

def preprocessing_file(file_path):
    out = []
    with open(file_path,'r') as f_in:
        lines = csv.reader(f_in)
        next(lines)
        out.append(lines)
    return out

when I run this code the terminal shows me messages below

  File "preprocessing.py", line 14, in preprocessing_file
    next(lines)
StopIteration

This problem occur after I make these section a function, before it the code works fine.

Anyone know whats the problem?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
張軒銘
  • 130
  • 1
  • 13

1 Answers1

2

You opened an empty file; there are no rows to iterate over. You can tell next() to suppress the exception by giving it a default value to return:

next(lines, None)

See Skip the headers when editing a csv file using Python.

Note that your out.append(lines) line appends the CSV reader object to your list, not the rows in the CSV. I'd use out = list(lines) for that instead, or just return the reader itself with return lines.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343