我要从特定行开始读取文件,一次读取 N 行。到目前为止,我一次读了 N 行:
from itertools import islice
n = 10
with open(fname, 'r') as f:
while True:
next_n_lines = list(islice(f, n))
for line in next_n_lines:
print line.rstrip()
if not next_n_lines:
break
关于从特定行号开始阅读它的任何帮助。
最佳答案
有一个使用 itertools.islice
的简单解决方案:
N = 100 # starting line number
n = 10 # size of a chunk
with open(fname) as f:
f = islice(f, N, None) # creates an iterator that starts after N lines
while True:
next_n_lines = list(islice(f, n))
for line in next_n_lines:
print line.rstrip()
if not next_n_lines:
break
关于python - 一次从特定行和 N 行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701814/