开发者

subscripting a specific line from python's csv reader?

开发者 https://www.devze.com 2023-01-06 10:56 出处:网络
i\'d like to be able to access specific li开发者_开发问答nes of a csv file through the csv reader.For example, the fourth line.Is there a way to do this with python\'s csv reader module?You just have

i'd like to be able to access specific li开发者_开发问答nes of a csv file through the csv reader. For example, the fourth line. Is there a way to do this with python's csv reader module?


You just have to parse all the CSV file, and then use normal sequencing indexing.

Otherwise, you can do something like this

def my_filter(csv_file, lines):
   for line_number, line in enumerate(csv_file):
       if line_number in lines:
          yield line

my_file = open("file.csv")
my_reader = csv.reader(my_filter(my_file, (3,)))

Note that you can't avoid parsing the whole file, in a way or in another, because the lines are of variable lenght. The line count only advances when a '\n' is found, and it has to be found in a character by character basis.

Also, this filter won't work if you happen to have newline characters inside quotes in the csv file -- probably you are just better off parsing the whole file to a list, and retrieving the indexes from there, anyway:

my_file = open("file.csv")
my_reader = csv.reader(my_file)
my_line = list(my_reader)[3]

update Most important: if you need random access to information which is far too large to fit in memory, just consider dumping it to a SQL database instead. It will spare one reinventing a lot of wheels.

0

精彩评论

暂无评论...
验证码 换一张
取 消