Python csv seek() 不工作

Python csv seek() not working

您好,我正在尝试使用以下代码读取 csv 文件。我想从提供的 csv 文件的第 n 行读取到第 m 行。例如,我想从第 10 行开始阅读到第 100 行,然后从第 500 行开始阅读到第 1000 行。我使用 startend 变量给出这些参数。

问题 无论开始和结束变量如何,它总是从头开始。 我试了又试了一个解决方案,但 failed.Can 谁能帮我弄清楚这里的问题。?非常感谢! (有一些重复的问题,但似乎没有人给出解决方案)


    import csv
    import os

    with open('file.csv','r') as csvfile:
        start=10
        end=100
        csvfile.seek(start)
        r= csv.reader(csvfile)
        r.next()
        for i in range(start,end):
            try:
                url=r.next()[2]
                print url
            except IndexError,e:
                print str(e),
            except ValueError,b:
                print b
        csvfile.close()

使用csv模块。

import csv

n = 3
m = 5

read = 0
with open("so.csv") as csvfile:
    reader = csv.reader(csvfile)
    for record in reader:
        read += 1
        if read >= n and read <= m:
            print(record)

您可以像这样遍历 csv 文件行并获取您想要的行:

import csv

def read_lines(file_name, start, end):
    with open(file_name, 'rb') as csvfile:
        csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in csvreader:
            if csvreader.line_num >= start and csvreader.line_num <= end:
                print ', '.join(row)
            else:
                continue

read_lines('test.csv', 10,12)

更新:

来自文档:csvreader.line_num: The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.