Python中的多行文件读取

Python中的多行文件读取

本文介绍了Python中的多行文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



任何想法如何能达到这个目标?

解决方案

您正在寻找:

  with open('data.txt' )作为f:
lines = []
而真:
line = list(islice(f,10))#islice返回一个迭代器,所以在这里将它转换为列表。
if line:
#在这里有一些当前设置为< = 10的行
lines.append(line)#可以存储它
else:
break
打印行


I am looking for a method in Python which can read multiple lines from a file(10 lines at a time). I have already looked into readlines(sizehint), I tried to pass value 10 but doesn't read only 10 lines. It actually reads till end of the file(I have tried on the small file). Each line is 11 bytes long and each read should fetch me 10 lines each time. If less than 10 lines are found then return only those lines. My actual file contains more than 150K lines.

Any idea how I can achieve this?

解决方案

You're looking for 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中的多行文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:49