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

标签 python

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

相关文章:

Python logging.info() 不记录消息

python 条件调试断点单行代码,适用于 3.7 PEP 553 之前的版本,其行为类似于 Perl 的 $DB::single=1

python - 如何使用 MongoDB 2.4 对 2d 或 2dsphere 索引字段使用常规查询

python - 在 Python 中,为什么不能在使用 subprocess 创建文件后立即对其进行解析?

python - 与模式匹配且不包含某些单词的字符串

python - 仅针对特定列中的某些条件值,使用之前的值填充每组每小时缺失的日期

python - Django:相互引用的静态文件。

python - 在文件中写入了一些变量名,需要使用 python 将其替换为新生成的随机值?

python - 查找有多少高于标准开发值

python - 将组上的顺序计数器列添加到 pandas 数据框