简体   繁体   中英

Split a text file in Python by number of lines

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

ie I need the output in this format of lines [AB C D, AB C D, AB 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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM