用Python读取多行文件

Rak*_*esh 1 python file file-read

我正在寻找一种Python方法,它可以从文件中读取多行(一次10行).我已经调查过readlines(sizehint),我试图传递值10,但不会只读取10行.它实际上读到文件的末尾(我已经尝试过小文件).每行长11个字节,每次读取每次应取10行.如果找到少于10行,则仅返回那些行.我的实际文件包含超过150K行.

知道我怎么能做到这一点?

Ash*_*ary 8

您正在寻找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    
Run Code Online (Sandbox Code Playgroud)