开发者

Copy from a file until a certain marker string is found

开发者 https://www.devze.com 2023-01-21 22:09 出处:网络
I am trying to write some code which will open List1.txt and copy the contents up until it sees the string \'John smith\' to List2.txt.

I am trying to write some code which will open List1.txt and copy the contents up until it sees the string 'John smith' to List2.txt.

This is what I have so far:

F=open('C:\T\list.txt','r').readlines()
B=开发者_Go百科open('C:\T\list2.txt','w')
BB=open('C:\T\list2.txt','r').readlines()
while BB.readlines() == 'John smith':
    B.writelines(F)

Here is an example of what List1.txt could contain:

Natly molar
Jone rock
marin seena
shan lra
John smith
Barry Bloe
Sara bloe`

However, it doesn't seem to be working. What am I doing wrong?


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)


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消