I have a file containing some lines of code followed by a string pattern. I need to write everything before the line containing the string pattern in file one and everything after the string pattern in file two:
e.g. (file-content)
The output should be file one with codeline 1, codeline 2 and file two with codeline 3.
I am familiar with writing files, but unfortunately I do not know how to determine the content before and after the string pattern.
If the input file fits into memory, the easiest solution is to use str.partition()
:
with open("inputfile") as f:
contents1, sentinel, contents2 = f.read().partition("Sentinel text\n")
with open("outputfile1", "w") as f:
f.write(contents1)
with open("outputfile2", "w") as f:
f.write(contents2)
This assumes that you know the exact text of the line separating the two parts.
This approach is similar to Lev's but uses itertools
because it's fun.
dont_break = lambda l: l.strip() != 'string_pattern'
with open('input') as source:
with open('out_1', 'w') as out1:
out1.writelines(itertools.takewhile(dont_break, source))
with open('out_2', 'w') as out2:
out2.writelines(source)
You could replace the dont_break function with a regular expression or anything else if necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With