how to merge file lines having the same first word in python?

Posted by user1377135 on Stack Overflow See other posts from Stack Overflow or by user1377135
Published on 2014-06-09T15:21:32Z Indexed on 2014/06/09 15:24 UTC
Read the original article Hit count: 235

I have written a program to merge lines in a file containing the same first word in python. However I am unable to get the desired output. Can anyone please suggest me the mistake in my program?

input

"file.txt"
line1: a b c
line2: a b1 c1
line3: d e f
line4: i j k
line5: i s t 
line6: i m n 

`

output

a b c a b1 c1 d e f i j k i s t i m n

my code

a = [line.split() for line in open('file.txt')] L=[] for i in range(0,len(a)): j=i while True: if a[j][0] == a[j+1][0]: L.append(a[j]) L.append(a[j+1]) j=j+2 else: print a[i] print L break

© Stack Overflow or respective owner

Related posts about python

Related posts about debugging