1

How can I split a single .txt file into two or more .txt files when a white line occours?

Here is a example of what my txt looks like:

a s d d d d s d f
f d e s s a d f s
a s d d d d s d f
f d e s s a d f s

dsdesd
dseesdse

I would like to know how to split this single text file into:

First txt file:

a s d d d d s d f
f d e s s a d f s
a s d d d d s d f
f d e s s a d f s

Second txt file:

dsdesd
dseesdse
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
LRA98
  • 33
  • 1
  • 6

1 Answers1

2

If you know the file will only have one blank line, you can split the contents at the double newline character:

with open('input.txt') as f:
    contents = f.read()

output1, output2 = contents.split('\n\n')

with open('output1.txt', 'w') as o1:
    o1.write(output1)

with open('output2.txt', 'w') as o2:
    o2.write(output2)

If your file has more than one blank line this will fail as the split will return more than 2 parts and try to assign them to only two names, output1 and output2. split can be told to only split a maximum amount of times so it may be safer to say:

output1, output2 = contents.split('\n\n', 1)

If there are two or more blank lines, output1 will be the contents up to the first blank line. output2 will be everything after the first blank line, including any further blank lines.

Of course, this can fail if there are no blank lines.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99