python - 在 Python 中读取多行文件

标签 python file file-read

我正在寻找 Python 中的一种方法,它可以从文件中读取多行(一次 10 行)。我已经研究过 readlines(sizehint),我试图传递值 10 但不只读取 10 行。它实际上一直读取到文件末尾(我试过小文件)。每行长 11 个字节,每次读取应该每次获取 10 行。如果找到的行少于 10 行,则只返回这些行。我的实际文件包含超过 15 万行。

知道如何实现吗?

最佳答案

您正在寻找 itertools.islice() :

with open('data.txt') as f:
    lines = []
    while True:
        line = list(islice(f, 10)) #islice returns an iterator ,so you convert it to list here.
        if line:                     
            #do something with current set of <=10 lines here
            lines.append(line)       # may be store it 
        else:
            break
    print lines    

关于python - 在 Python 中读取多行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790983/

相关文章:

Python anaconda 访问被拒绝

python - 通过两个单独的域访问 Django Web 应用程序

c++ - C++ 中的动态分配不检查数组边界?

c++ - 如何在 C++ 中正确读取和覆盖同一个文件

c - fread 不读取多行

python - Python 的 struct.pack 到底做了什么?

python - 如何在 Jupyter Notebook 中禁用单元格截断?

javascript - 在javascript中从文本文件中读取数据

Java读取长文本文件很慢

java - 用java读取html文件