views:

42

answers:

2

hello guys i tried to do that code but it's not work :(

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)

so how i can told my python : go to copy from file : List1.txt to List2.txt but if you found John smith stop copying and close !

List1.txt:
Natly molar
Jone rock
marin seena
shan lra
John smith
Barry Bloe
Sara bloe`
A: 
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()
jdizzle
+2  A: 
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)
SilentGhost
FYI, you have a typo: takewile
Jason Mock
Nice answer, but I'd say that using itertools.takewhile() with a lambda plus two opens in a with statement pretty much outs the OP as having had assistance on his homework.
hughdbrown
@hughdbrown: that's probably why OP accepted jdizzle's answer
SilentGhost
So, `takewhile()` is reading from `fout`? `fin` is not actually used in your code. Say, have you actually tested this code?
hughdbrown
@hughdbrown: no it was intentional, I was wondering what kind of behaviour I'll elicit with this sort of typo.
SilentGhost
@SilentGhost: So you write solutions to homework that the OP cannot submit and you intentionally put bugs in the code?
hughdbrown
@hugh: let's review this again: (1) typo, (2) sarcasm, (3) writing pythonic code for easiest of answer is wrong because some one might not understand it. did I miss anything? Well this anything is not my pint, see ya tomorrow.
SilentGhost