在python2中使用csv时停止迭代
在我的代码中,有一个函数包含如下csv读取器在python2中使用csv时停止迭代,python,csv,Python,Csv,在我的代码中,有一个函数包含如下csv读取器 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 当我运行此代码时,终端会在下面显示消息 File "preprocessing.py",
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
当我运行此代码时,终端会在下面显示消息
File "preprocessing.py", line 14, in preprocessing_file
next(lines)
StopIteration
这个问题发生在我将这些部分设置为函数之后,在此之前代码工作正常
有人知道是什么问题吗?你打开了一个空文件;没有要迭代的行。您可以告诉
next()
next(lines, None)
看
请注意,out.append(行)
行将CSV阅读器对象附加到列表中,而不是CSV中的行。我会使用out=list(lines)
来代替它,或者用returnlines
返回阅读器本身