我有一个文件包含一些代码行,后跟一个字符串模式.我需要在文件一中包含字符串模式的行之前写入所有内容,并在文件二中的字符串模式之后写入所有内容:
例如(文件内容)
输出应该是带有代码行1的文件1,代码行2和带有代码行3的文件2.
我熟悉编写文件,但不幸的是我不知道如何确定字符串模式之前和之后的内容.
如果输入文件适合内存,最简单的解决方案是使用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)
Run Code Online (Sandbox Code Playgroud)
这假定您知道将两个部分分开的线的确切文本.
这种方法类似于Lev's,但itertools因为它很有趣.
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)
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以使用正则表达式或其他任何内容替换dont_break函数.
| 归档时间: |
|
| 查看次数: |
3865 次 |
| 最近记录: |