Python Forum
Split Characters As Lines in File - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Split Characters As Lines in File (/thread-31684.html)



Split Characters As Lines in File - quest_ - Dec-27-2020

Hello,
I have this txt file. (The length is 15000)
1010100101010110000000000001111111111
And according to input, I want to separate my numbers as different lines and each line will have equal size
For instance, suppose that i is the input and i =10
then my text file will become like that:
1010100101
0101011000
0000000000...

The code should be something like that
with open("names.txt","r") as f:
    input_list = f.read()    

def write_len(input_list):
    final_str = "\n".join([str(len(item)) for item in input_list])

    with open("name_length.txt","w") as w:
        w.write(final_str)

    return 1
But I couldn't complete it
Can you please help me?
Best


RE: Split Characters As Lines in File - bowlofred - Dec-28-2020

You could loop over every character in the string, assembling them into strings of the proper length.

Or you could slice it into sections of the proper length.

k = 10
sections = [input_list[i:i+k] for i in range(0, len(input_list), k)]
Then you can join() the sections or print them or whatever you want with them.


RE: Split Characters As Lines in File - perfringo - Dec-28-2020

There is built-in module textwrap:

>>> import textwrap
>>> s = '1010100101010110000000000001111111111'
>>> print('\n'.join(textwrap.wrap(s, width=10)))
1010100101
0101100000
0000000111
1111111



RE: Split Characters As Lines in File - quest_ - Dec-28-2020

(Dec-28-2020, 04:48 AM)perfringo Wrote: There is built-in module textwrap:

>>> import textwrap
>>> s = '1010100101010110000000000001111111111'
>>> print('\n'.join(textwrap.wrap(s, width=10)))
1010100101
0101100000
0000000111
1111111

Many thank to both of you
here is my final code
import itertools
import random
from collections import defaultdict
import pprint
import fileinput
import textwrap

with open("line500_.txt","r") as f:
    input_list = f.read()    
 
k = 10
#sections = [input_list[i:i+k] for i in range(0, len(input_list), k)]
#final_str = "\n".join([str(len(item)) for item in input_list])
#final = "\n".join(str(sections))
 
twrap =  '\n'.join(textwrap.wrap(input_list, width=10))
print(twrap)   

myfile =  open("name_length.txt","w")
with open("name_length.txt","w") as w:
    w.write(str(twrap))