How to read specific lines of a large csv file

后端 未结 4 1093
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 10:21

I am trying to read some specific rows of a large csv file, and I don\'t want to load the whole file into memory. The index of the specific rows are given in a list L

4条回答
  •  悲&欢浪女
    2021-01-02 11:08

    Assuming L is a list containing the line numbers you want, you could do :

    with open("~/file.csv") as f:
        r = csv.DictReader(f)
        for i, line in enumerate(r):
            if i in L:    # or (i+2) in L: from your second example
                print line
    

    That way :

    • you read the file only once
    • you do not load the whole file in memory
    • you only get the lines you are interested in

    The only caveat is that you read whole file even if L = [3]

提交回复
热议问题