-2

My file is this one:

14
3
21
37
48
12
4
6
22
4

How can I read M number at time? for example 4 at time. Is it necessary to use two for loops?

My goal is to create (N/M)+1 lists with M numbers inside every lists, except the final list (it's the reminder of division N/M)

Lorenzo Vannucchi
  • 359
  • 1
  • 3
  • 11

4 Answers4

0

Use 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]

Previous answer: Iterate over a file (N lines) in chunks (every M lines), forming a list of N/M+1 lists.

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]]
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
0

You can use python list slice operator to fetch the number of required elements from a file by reading a file using readlines() where each element of list will be one line of file.

with open("filename") as myfile:
    firstNtoMlines = myfile.readlines()[N:N+M] # the interval you want to read
    print firstNtoMlines
Tanu
  • 1,503
  • 12
  • 21
0

Now my code is this one:

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

so, It should work. My file's got 633 numbers

Lorenzo Vannucchi
  • 359
  • 1
  • 3
  • 11
-1

This has been asked before.

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

For the case of grouping lines in a file into lists of size 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

Community
  • 1
  • 1
gnicholas
  • 2,041
  • 1
  • 21
  • 32