读取csv文件中的特定行,python [英] read specific line in csv file , python

查看:3096
本文介绍了读取csv文件中的特定行,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用python的 CSV 文件中,我们可以逐行或逐行读取所有文件,我想读取特定行(行号24示例)而不读取所有文件和所有行。

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

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


从文件命名文件名获取行lineno。这个函数将永远不会引发异常 - 它会返回错误(对于找到的行,将包含终止换行符)。

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)

或使用使用itertools中的食谱移动指针:

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)

这篇关于读取csv文件中的特定行,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆