Python を使用したCSVファイルでは、すべてのファイルを行ごとまたは行ごとに読み取ることができます。すべてのファイルとすべての行を読み取ることなく、特定の行 (行番号 24 の例) を読み取りたいです。
7071 次
2 に答える
8
linecache.getlineを使用できます:
linecache.getline(ファイル名, lineno[, module_globals])
filename という名前のファイルから行 lineno を取得します。この関数は決して例外を発生させません — エラーの場合は '' を返します (見つかった行には終了改行文字が含まれます)。
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)
于 2015-06-21T12:00:07.387 に答える