CSV reads a specific line

I have a CSV file with 100 lines.

How to read certain lines?

I want to read the words the 9th line or the 23rd line, etc.

+5
source share
4 answers

You can use list comprehension to filter the file as follows:

 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 
+6
source

You can read them all and then use regular 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, it can kill your memory, but if the file received less than 10,000 lines, you should not face big slowdowns.

+2
source

You just skip the required number of lines:

 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 
+1
source

Use list to immediately capture all the lines as a list. Then access your target lines by index / offset in the list. For instance:

 #!/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
source

Source: https://habr.com/ru/post/1205083/


All Articles