【发布时间】:2015-09-06 23:27:32
【问题描述】:
在使用 python 的CSV 文件中,我们可以逐行或逐行读取所有文件,我想读取特定行(第 24 行示例)而不读取所有文件和所有行。
【问题讨论】:
在使用 python 的CSV 文件中,我们可以逐行或逐行读取所有文件,我想读取特定行(第 24 行示例)而不读取所有文件和所有行。
【问题讨论】:
你可以使用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)
【讨论】:
for line in f:...时,next被重复调用
for line in f... 即可读取其余行。
或者,您可以在 pandas 中利用 nrows 和 skiprows 参数
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)))
【讨论】: