Python:从文件中读取N数,M是时间

时间:2016-05-15 18:24:33

标签: python file io

我的档案就是这个:

14
3
21
37
48
12
4
6
22
4

我怎样才能及时阅读M号码?例如4时。是否有必要使用两个 for 循环?

我的目标是在每个列表中创建(N / M)+1个列表,其中包含M个数字,但最终列表除外(它是分组N / M的提醒)

4 个答案:

答案 0 :(得分:0)

使用itertools.islice

import itertools 
import math

filename = 'test.dat'
N = 9
M = 4

num_rest_lines = N
nrof_lists = int(math.ceil(N*1.0/M))

with open(filename, 'r') as f:
    for i in range(nrof_lists):
        num_lines = min(num_rest_lines, M)
        lines_gen =  itertools.islice(f, num_lines)

        l = [int(line.rstrip()) for line in lines_gen]
        num_rest_lines = num_rest_lines - M

        print(l)    
        # Output
        [14, 3, 21, 37]
        [48, 12, 4, 6]
        [22]

上一个回答:以块(每N行)对文件(M行)进行迭代,形成N/M+1列表列表。

import itertools 

def grouper(iterable, n, fillvalue=None):
    """iterate in chunks"""
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

# Test
filename = 'test.dat'
m = 4
fillvalue = '0'

with open(filename, 'r') as f:
    lists = [[int(item.rstrip()) for item in chuck] for chuck in grouper(f, m, fillvalue=fillvalue)]
    print(lists)
    # Output
    [[14, 3, 21, 37], [48, 12, 4, 6], [22, 4, 0, 0]]

答案 1 :(得分:0)

现在我的代码就是这个:

N = 4
M = 0

while (M < 633):
    with open("/Users/Lorenzo/Desktop/X","r") as myFile:
        res = myFile.readlines()[M:N]
        print(res)
    M+=4
    N+=4

所以,它应该工作。我的文件有633个数字

答案 2 :(得分:-1)

以前曾经问过这个问题。

from itertools import izip_longest
izip_longest(*(iter(yourlist),) * yourgroupsize)

对于将文件中的行分组为大小为4的列表的情况:

with open("file.txt", "r") as f:
    res = izip_longest(*(iter(f)),) * 4)
    print res

Alternative way to split a list into groups of n

答案 3 :(得分:-1)

您可以使用python list slice运算符通过使用readlines()读取文件来从文件中获取所需元素的数量,其中list的每个元素都是一行文件。

with open("filename") as myfile:
    firstNtoMlines = myfile.readlines()[N:N+M] # the interval you want to read
    print firstNtoMlines