0

I have a txt file in below format and i want to split this file in such a way that it split the file after 4th line in one list list.

Input file:

1 A
2 B
3 C
4 D
5 A
6 B
7 C
8 D
9 A
10 B
11 C
12 D

i.e. I need the output in this format of lines [A B C D, A B C D, A B C D]

I tried below code but its not helping me out

f = open("demoFile.txt", "r")

for line in f:
   with open("demoFile.txt", 'r') as infile:
    lines = [line for line in infile][:4]
    print(lines)
Suyash
  • 37
  • 6

2 Answers2

0

IIUC, you could use the grouper recipe from itertools:

from itertools import zip_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 zip_longest(*args, fillvalue=fillvalue)


with open('data.txt') as infile:
    groups = [' '.join(group) for group in grouper(map(str.rstrip, infile), 4)]
    print(groups)

Output

['A B C D', 'A B C D', 'A B C D']

Notice that you can change the output to a list of list like this, for example:

groups = [list(group) for group in grouper(map(str.rstrip, infile), 4)]

This will return this instead:

[['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D']]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

You could use something like the generator defined here: https://stackoverflow.com/a/312464/9397585

Remember you first need to convert the file to a list.

Your code should look like this:

f = [line for line in open("demoFile.txt", "r")]

lines = []

for i in range(0, len(f), 4):
    lines.append(f[i:i + 4])

print(lines)
Dodilei
  • 188
  • 2
  • 12
  • And if you want a list of strings (with the 4 lines together) rather than a list of lists, use str.join(f[i:i+4]) inside lines.append(). – Dodilei Nov 17 '19 at 15:54