0

Typically, when reading a file, I use the for line n fileobject: construct. Is there a simple way to just loop over the first N (or some arbitrary subset) of lines in a file, so that I don't have to read in the entire file?

4

3 に答える 3

4

これは、あなたの望むことですか:

file = open('path/to/File.txt', 'r')
for i in range(1,n):
   file.readline()

詳細については、こちらを参照してください: Python の入力と出力

于 2012-11-19T17:51:21.893 に答える
2

これを試して:

import itertools

f = open(filename, 'r')
N = 10 # Number of lines to take

for line in itertools.islice(f, N):
    pass # Your code here
于 2012-11-19T17:50:40.080 に答える
0

を使用できますitertool.islice。たとえば、6 行目から 10 行目を読みたい場合は、次のようにします。

In [66]: with open("data1.txt") as f:
           lines=list(islice(f,5,10,1))
           print lines
于 2012-11-19T17:53:02.187 に答える