我正在做一个python项目。我打开了一个新的csv文件,其内容是
Python 3.4.6 (default, Mar 20 2017, 20:03:28)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
我正在做的是......
A | B
-------------
1. 200 | 201
2. 200 | 202
3. 200 | 201
4. 200 | 203
5. 201 | 201
6. 201 | 202
...........
问题是我只能打印一次值。def csvvalidation(readers):
for row in readers:
print row
def checkduplicationcsv(reader):
datalist = []
for row in reader:
print row
content = list(row[i] for i in range(0,3))
datalist.append(content)
with open("new.csv", "rb") as infile:
reader = csv.reader(infile)
first_row = next(reader, None) # skip the headers
checkduplicationcsv(reader)
csvvalidation(reader)
函数阅读器无法正常工作。如何多次使用阅读器对象。我无法打印其行值。什么可以我呢?请给我一个解决方案。我不知道csvvalidation()
(我认为它再次指向同一个读者)。所以我在第一个函数之后尝试seek()
但没有用。没有发生
提前致谢。
答案 0 :(得分:3)
阅读器缠绕在一个文件指针上,当它用完时,它就用完了。不要多次使用它,使用一次然后使用您读取的数据数组:
with open("new.csv", "rb") as infile:
reader = csv.reader(infile)
first_row = next(reader, None) # skip the headers
data = list(reader) # read everything else into a list of rows
checkduplicationcsv(data)
csvvalidation(data)
是的,你的两个函数无需修改即可工作(除非它们已被破坏),因为列表,文件和csv阅读器都是可以迭代的“迭代”。不是Python盛大...
答案 1 :(得分:2)
有效。你应该再次检查你的代码:)
with open("new.csv", "rb") as infile:
reader = csv.reader(infile)
first_row = next(reader, None)
checkduplicationcsv(reader)
infile.seek(0) # <- Add infile.seek(0)
csvvalidation(reader)
答案 2 :(得分:2)
如果您无法将整个文件读入内存,则可以通过tee
创建两个阅读器:
from itertools import tee
with open("new.csv", "rb") as infile:
reader = csv.reader(infile)
first_row = next(reader, None) # skip the headers
reader1, reader2 = tee(reader, 2)
checkduplicationcsv(reader1)
csvvalidation(reader2)