Skip to main content
 首页 » 编程设计

python之一次从特定行和 N 行读取文件

2025年05月04日29TianFang

我要从特定行开始读取文件,一次读取 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