【问题标题】:read specific line in csv file , python读取csv文件中的特定行,python
【发布时间】:2015-09-06 23:27:32
【问题描述】:

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

【问题讨论】:

标签: python csv reader


【解决方案1】:

你可以使用linecache.getline:

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

从名为 filename 的文件中获取 lineno。此函数永远不会引发异常——它会在错误时返回 ''(找到的行将包含终止换行符)。

import linecache


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

或者使用 itertools 中的consume recipe 来移动指针:

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)

【讨论】:

  • @xtofl,一个文件对象是它自己的迭代器,当你for line in f:...时,next被重复调用
  • 并从特定行而不是从头开始阅读?它只需消耗(f,X)并每次增加X(在所需位置初始化X),感谢您的有用回答:)
  • @user3967257,如果您想从某一行开始,请使用消耗配方,要消耗的第二个参数是要消耗的行数,然后只需 for line in f... 即可读取其余行。
  • 这就是我在 range(X,limit) 中的意思:consume(f,i)
【解决方案2】:

或者,您可以在 pandas 中利用 nrowsskiprows 参数

line_number = 30
pd.read_csv('big.csv.gz', sep = "\t", nrows = 1, skiprows = line_number - 1)

记住skiprows 可以是一个列表,所以如果你需要标题使用

pd.read_csv('big.csv.gz', sep = "\t", nrows = 1, skiprows = list(range(1, line_number - 1)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多