4

I have a large string text file, I would like to split the string every 117 characters and put the next 117 chars on a newline, and so on until the end of the file.

I tried this:`s = """ I have removed the string for visibility reasons """ space = """

""" file = open('testoutput.txt', 'w') while s: print s[:10] output = output + s + """

"""
s = s[10:]

file.write(output) file.close() print "Done" `

but had the issue where the final output in the file looked like this cascading:` this [SHIFT]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations

T]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



le and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



 descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ts would av[BACKSPACE][BACKSPACE]vary because of mutations



v[BACKSPACE][BACKSPACE]vary because of mutations



E][BACKSPACE]vary because of mutations



CE]vary because of mutations



cause of mutations



utations

`

0

2 Answers 2

6
while s:
    print s[:117]
    s = s[117:]
Sign up to request clarification or add additional context in comments.

Comments

3

You can either split a buffer using the regular slicing syntax, or you may opt to split the file directly while reading it. This is an example of the second approach:

with open(r"/path/to/some/file") as input_file:
    line = input_file.read(117)
    while line:
        print len(line)
        line = input_file.read(117)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.