Python split the content of a file into approximately equal parts

#a = input text
#n = no of parts
def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))

#Example input and use case
#Text inside test.txt: This is what you came for
with open("test.txt", encoding="utf-8") as f:
    data = f.read()
    print(list(split(data, 3)))

#output: ['This is w', 'hat you ', 'came for']

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe