简体   繁体   English

Python-如何在读取csv文件时读取前几行?

[英]Python - How to read previous lines while reading csv file?

I want to read rows in excel table but when I want, during reading process, I would like to stop reading forward and I want to read previous lines (backward reading)? 我想读取excel表中的行,但是当我想要在读取过程中,我想停止向前读取并且我想读取前几行(向后读取)吗? How can I go previous rows again? 我如何才能再次进入上一行?

import csv

file = open('ff.csv2', 'rb')
reader = csv.reader(file)

for row in reader:
    print row

You could always store the lines in a list and then access each line using the index. 您始终可以将行存储在列表中,然后使用索引访问每一行。

import csv
file = open('ff.csv2', 'r')

def somereason(line):
    # some logic to decide if stop reading by returning True
    return False  # keep on reading

for row in csv.reader(file):
    if somereason(line):
        break

    lines.append(line)

# visit the stored lines in reverse
for row in reversed(lines):
   print(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM