python代码有个下标_从python的csv阅读器下标一个特定的行?

i'd like to be able to access specific lines 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值