从文件中复制直到找到特定标记字符串
我正在尝试写一些代码,目的是打开 List1.txt
文件,并把里面的内容复制到 List2.txt
文件,直到遇到字符串 'John smith'
为止。
这是我目前写的代码:
F=open('C:\T\list.txt','r').readlines()
B=open('C:\T\list2.txt','w')
BB=open('C:\T\list2.txt','r').readlines()
while BB.readlines() == 'John smith':
B.writelines(F)
这里有一个 List1.txt
文件可能包含的内容示例:
Natly molar
Jone rock
marin seena
shan lra
John smith
Barry Bloe
Sara bloe`
不过,这个代码似乎没有正常工作。我哪里出错了呢?
2 个回答
3
from itertools import takewhile
with open('List1.txt') as fin, open('List2.txt', 'w') as fout:
lines = takewhile(lambda x : x != 'John smith\n', fin)
fout.writelines(lines)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
F=open('C:\T\list1.txt','r')
B=open('C:\T\list2.txt','w')
for l in F: #for each line in list1.txt
if l.strip() == 'John Smith': #l includes newline, so strip it
break
B.write(l)
F.close()
B.close()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。