Python:读取文件并附加大量28行的列表

时间:2014-02-04 15:08:45

标签: python file-io python-3.x

读取包含10.000位数的文件。数字每行使用28行,所以我想读取文件并存储28个元素的列表。

with open(ima) as file:
    for linea in file:
        .
        .
        .

2 个答案:

答案 0 :(得分:0)

with open(ima) as file:
    file_list = f.readlines() # You will have a list with size/28=the number of digits
    # Divide file_list by size 28

答案 1 :(得分:0)

来自itertools文档,

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

您可以将其称为

with open(ima) as inf:
    for group in grouper(inf, 28, ""):
        # now group contains 28 lines from inf