Providing Python code for line-based chunk splitting
The approach reads buffered byte chunks, finds the last newline near each chunk's end, and splits there to avoid cutting lines. This method yields or writes chunks containing complete lines for efficient large-file splitting without breaking lines.
One simple way to do it is to treat the input as a stream and carry any “partial” line over into the next buffer. You never have to load the whole file into memory, and you only ever cut on a \n boundary.
Here's a complete example in Python that writes out part‑000, part‑001, … files of roughly max_bytes each but never splits a line:
import os
def split_on_lines(path, max_bytes, out_prefix, bufsize=1024*1024):
part = 0
current_size = 0
out = open(f'{out_prefix}{part:03d}', 'wb')
carry = b''
with open(path, 'rb') as src:
while True:
block = src.read(bufsize)
if not block:
break
data = carry + block
start = 0
while True:
nl = data.find(b'\n', start)
if nl == -1:
# no complete line left in this buffer
break
line = data[start:nl+1]
# roll over to a new file if this line would exceed max_bytes
if current_size + len(line) > max_bytes and current_size > 0:
out.close()
part += 1
current_size = 0
out = open(f'{out_prefix}{part:03d}', 'wb')
out.write(line)
current_size += len(line)
start = nl + 1
# whatever remains is an incomplete line; prepend to next block
carry = data[start:]
# write any trailing data that didn't end with a newline
if carry:
if current_size + len(carry) > max_bytes and current_size > 0:
out.close()
part += 1
out = open(f'{out_prefix}{part:03d}', 'wb')
out.write(carry)
out.close()
# usage
split_on_lines('largefile.txt', max_bytes=50_000_000, out_prefix='chunk-')
If you don't need to limit the output file size and just want to iterate over line‑aligned chunks, you can simplify it further:
def iter_chunks(f, bufsize=1024*1024):
carry = b''
while True:
block = f.read(bufsize)
if not block:
if carry:
yield carry
break
data = carry + block
last_nl = data.rfind(b'\n')
if last_nl == -1:
# no newline in the buffer, carry everything over
carry = data
continue
yield data[:last_nl+1]
carry = data[last_nl+1:]
Both approaches read in buffered chunks, look for newline characters near the chunk boundary, and make sure that the split points coincide with line breaks so that no text line is cut in half.