CSV read specific row

后端 未结 5 774
鱼传尺愫
鱼传尺愫 2020-12-03 07:27

I have a CSV file with 100 rows.

How do I read specific rows?

I want to read say the 9th line or the 23rd line etc?

相关标签:
5条回答
  • 2020-12-03 07:54

    You can do something like this :

    with open('raw_data.csv') as csvfile:
        readCSV = list(csv.reader(csvfile, delimiter=','))
        row_you_want = readCSV[index_of_row_you_want]
    
    0 讨论(0)
  • 2020-12-03 07:55

    You could use a list comprehension to filter the file like so:

    with open('file.csv') as fd:
        reader=csv.reader(fd)
        interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
    # now interestingrows contains the 28th and the 62th row after the header
    
    0 讨论(0)
  • 2020-12-03 08:00

    You simply skip the necessary number of rows:

    with open("test.csv", "rb") as infile:
        r = csv.reader(infile)
        for i in range(8): # count from 0 to 7
            next(r)     # and discard the rows
        row = next(r)   # "row" contains row number 9 now
    
    0 讨论(0)
  • 2020-12-03 08:00

    Use list to grab all the rows at once as a list. Then access your target rows by their index/offset in the list. For example:

    #!/usr/bin/env python
    
    import csv
    
    with open('source.csv') as csv_file:
        csv_reader = csv.reader(csv_file)
        rows = list(csv_reader)
    
        print(rows[8])
        print(rows[22])
    
    0 讨论(0)
  • 2020-12-03 08:04

    You could read all of them and then use normal lists to find them.

    with open('bigfile.csv','rb') as longishfile:
        reader=csv.reader(longishfile)
        rows=[r for r in reader]
    print row[9]
    print row[88]
    

    If you have a massive file, this can kill your memory but if the file's got less than 10,000 lines you shouldn't run into any big slowdowns.

    0 讨论(0)
提交回复
热议问题