0

I know to split a file by lines, you can do f.readlines(), but what if I was trying to split a file by every n lines? For example, I have a file

line1
line2
line3
line4
line5
line6
line7
line8

instead of looping through it line by line, I want to loop through it by every two lines, so it would output

line1
line2

line3
line4

etc

martineau
  • 119,623
  • 25
  • 170
  • 301
Hugh67945
  • 21
  • 3

2 Answers2

1

when you loop, you can get the index of the line with enumerate() and split there

collection = []
sub_collection = []
with open("test.txt") as fh:
    for index, line in enumerate(fh, 1):  # file-likes are iterable by-lines
        sub_collection.append(line)
        if index % 2 == 0:  # modulus is 0 every Nth line
            collection.append("".join(sub_collection))
            sub_collection = []
>>> collection
['line1\nline2\n', 'line3\nline4\n', 'line5\nline6\n', 'line7\nline8\n']
ti7
  • 16,375
  • 6
  • 40
  • 68
1

You can create a function to chunk an array next way

def chunked(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

And then use it with readlines

f = open('file.txt', 'r')
for l in chunked(f.readlines(), 2):
  # do anything with chunk
f.close()
geobreze
  • 2,274
  • 1
  • 10
  • 15