[Tutor] hiya

Kent Johnson kent37 at tds.net
Tue Feb 5 14:43:04 CET 2008


aaron meredith wrote:
> i have tried to do this so many different ways but im not sure how to do 
> it, i have a file with say multiple lines in it, it has a word in each 
> line i want to keep but i also need the kept word in every first and 
> second line joined together with some text in the middle

I would do this with an explicit iterator and a loop which processes a 
group of lines each time through the loop:

f = '''line test 6 tree  /keptpart/1_1/ word test

line test 6 tree  /keptpart/2_2/ test word

line test 6 tree  /keptpart/3_1/ word test

line test 6 tree  /keptpart/4_2/ test word

line test 6 tree  /keptpart/5_1/ word test

line test 6 tree  /keptpart/6_2/ test word

line test 6 tree  /keptpart/7_1/ word test

line test 6 tree  /keptpart/8_2/ test word'''.splitlines()

# You would use
# f = open('myfile.txt')

# Get an explicit iterator for access to next()
it = iter(f)

try:
     for line in it:
         kept1 = line.split()[4]
         it.next()
         line = it.next()
         kept2 = line.split()[4]
         print kept1, 'joined to', kept2
         it.next()
except StopIteration:
     pass


Kent


More information about the Tutor mailing list