[Solved] How do I split a text file into multiple text files by 25 lines using python? [closed]


You could try chunking every 25 lines, then write them each out to separate files:

def chunks(l, n):
    """Chunks iterable into n sized chunks"""
    for i in range(0, len(l), n):
        yield l[i:i + n]

# Collect all lines, without loading whole file into memory
lines = []
with open('FileA.txt') as main_file:
    for line in main_file:
        lines.append(line)

# Write each group of lines to separate files
for i, group in enumerate(chunks(lines, n=25), start=1):
    with open('File%d.txt' % i, mode="w") as out_file:
        for line in group:
            out_file.write(line)

Note: The chunking recipe from How do you split a list into evenly sized chunks?.

4

solved How do I split a text file into multiple text files by 25 lines using python? [closed]