python读取csv文件指定行和列,读取csv文件中的特定行,python

In an CSV file with python we can read all the file line by line or row by row , I want to read specific line (line number 24 example ) without reading all the file and all the lines.

解决方案

linecache.getline(filename, lineno[, module_globals])

Get line lineno from file named filename. This function will never raise an exception — it will return '' on errors (the terminating newline character will be included for lines that are found).

import linecache

line = linecache.getline("foo.csv",24)

Or use the consume recipe from itertools to move the pointer:

import collections

from itertools import islice

def consume(iterator, n):

"Advance the iterator n-steps ahead. If n is none, consume entirely."

# Use functions that consume iterators at C speed.

if n is None:

# feed the entire iterator into a zero-length deque

collections.deque(iterator, maxlen=0)

else:

# advance to the empty slice starting at position n

next(islice(iterator, n, n), None)

with open("foo.csv") as f:

consume(f,23)

line = next(f)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值