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)
- codeline 1
- codeline 2
- string pattern
- codeline 3
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()
: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.You could replace the dont_break function with a regular expression or anything else if necessary.
You need something like:
replace the line with startswith with a test that works on your pattern (using pattern matching from re if necessary, but anything that finds the devider line will do).
A more efficient answer which will handle large files and consume a limited amount of memory..
will work with large files since it works line by line. Assumes
string pattern
occurs only once in the input file. I like thestr.partition()
approach best if the whole file can fit into memory (which may not be a problem)Using
with
ensures the files are automatically closed when you are done, or an exception is encountered.No more than three lines: