我想循环遍历csv文档,并经常检查下一行的值,但坚持使用相同的行号。 .next()正在跳过一行,这对我不起作用,除非我能以某种方式再次返回。这样做有一个简单的方法吗?我尝试了成对/循环但是如果文件很大则需要太长时间。 我的示例代码是:
file1 = open("name.csv", 'rb')
reader = csv.DictReader(file1)
new_rows_list = []
for row in reader:
if row['IsFixated'] == 'TRUE':
new_row = [row['Result'], 'Fixation']
new_rows_list.append(new_row)
else:
new_row = [row['Result'], 'Saccade']
new_rows_list.append(new_row)
nextRow = reader.next() # check for next row ??
if nextRow['IsFixated'] == 'TRUE':
new_rows_list = CheckPreviousPositions(new_rows_list)
file1.close()
答案 0 :(得分:2)
reader1,reader2 = itertools.tee(csv.DictReader(file1))
#this creates two copies of file iterators for the file
next(reader2) #skip first line in second filehandle
for line,next_line in itertools.izip(reader1,reader2):
#do something?
我想......也许?
答案 1 :(得分:0)
如果你只需要检查下一行,那么这个生成器函数应该可以解决这个问题
def next_reader(file_name):
with open(file_name) as f:
reader = csv.reader(f)
check = 0
curr_and_next = []
while True:
if check == 0:
first = reader.next()
second = reader.next()
curr_and_next = [first, second]
check = 1
else:
curr_and_next = [curr_and_next[1], reader.next()]
yield curr_and_next
这将打开您的文件并将第一行和第二行添加到curr_and_next
列表并返回它。在任何后续调用中,它会将curr_and_next中的第二个值移动到第一个点,然后将文件中的下一行添加到第二个点。现在,这个生成器不会一次产生一行,而是生成一个包含下一行和后面一行的列表。例如,如果您的csv文件alpha.csv包含行:
a,b
c,d
e,f
你有一个循环:
for x in next_reader('alpha.csv'):
print x
这将打印:
[['a','b'],['c','d']]
[['c','d'],['e','f']]
请注意,csv文件中的最后一行只会在最后一次迭代中出现一次。 (对于最后一次打印,你不会得到像[['e','f'],None]
这样的东西。)