Python 如何多次使用csv阅读器对象
我正在做一个python项目。我打开了一个新的csv文件,它的内容是Python 如何多次使用csv阅读器对象,python,csv,reader,Python,Csv,Reader,我正在做一个python项目。我打开了一个新的csv文件,它的内容是 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
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()
(我认为它再次指向同一个读取器)所以我在第一个函数之后尝试了infle.seek(0)
,但是没有用。什么都没有发生
提前感谢。读卡器被一个文件指针包围,当文件指针用完时,它就用完了。不要多次使用它,只使用一次,然后使用您读取的数据数组:
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 grand吗…它可以工作。您应该再次检查代码:)
以open(“new.csv”、“rb”)作为填充:
reader=csv.reader(infle)
第一行=下一行(读卡器,无)
CheckReplicationCSV(读卡器)
infle.seek(0)#如果无法将整个文件读入内存,可以通过以下方式创建两个读取器:
它将读取文件中的所有内容。试试看。或者查找list()
。谢谢您的回答。如果不使用list,我可以使用它吗?我不知道如何回答。你为什么不想使用列表呢?你想做什么呢?看看我的问题我试过这个方法,但它不起作用。然后我想问题可能是打开文件的方式。我不使用这个方法打开文件。file=open('new.csv','rb')。所以我想这可能是problem@bobmarti这对我也有用。不知道为什么它不适合你。@bobmarti真的吗?至少在我的Python2.7环境中,该代码运行良好。让我们减少CSV文件中的数据,然后再试一次。@tellk我也在使用python 2.7。excel文件太大。我只将其减少为5行。但它不是working@bobmarti您是否将5行内容(CSV)和执行结果添加到问题部分?注意,您可能会丢失tee的一些功能,例如:“itertools.tee”对象没有属性“line\u num”
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)
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)