【问题标题】:Python - loop through csv file and check next linePython - 遍历 csv 文件并检查下一行
【发布时间】:2016-03-24 21:39:47
【问题描述】:

我想遍历一个 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()

【问题讨论】:

    标签: python csv


    【解决方案1】:
    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?
    

    我猜……也许吧?

    【讨论】:

      【解决方案2】:

      如果你只需要检查下一行,这个生成器函数应该可以解决问题

      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] 的信息)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        • 2017-08-06
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 2012-06-26
        相关资源
        最近更新 更多