从文件复制,直到找到某个标记字符串

时间:2010-10-21 15:46:53

标签: python file-io

我正在尝试编写一些代码,这些代码会打开List1.txt并复制内容,直到它看到字符串'John smith'List2.txt

这是我到目前为止所做的:

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 个答案:

答案 0 :(得分: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 :(得分: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()