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.