Python split the content of a file into approximately equal parts
1 min read

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

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×