JavaNewb
JavaNewb

Reputation: 35

Merging every two lines in a text file - Python

As the title says : is there an easy way of merging every two lines of a text file in python? For example my text file looks like this:

fname=xxx

uname=yyy

fname=zzz

uname=ppp

What I want as an output is :

fname=xxx uname=yyy

fname=zzz uname=ppp

and so on. Any help is appreciated!

Upvotes: 2

Views: 6780

Answers (3)

radicz
radicz

Reputation: 93

Here is another solution with sliding window, two lines at a time

with open("test.txt") as f:
    data = [x for x in f.read().split("\n") if x.strip() != ""] 
    for line1, line2 in list(zip(data, data[1:]))[::2]:
        print(" ".join([line1, line2]))

This will only work for files with even number of lines

Upvotes: 3

Cameron
Cameron

Reputation: 127

Instead of printing, you can append these to a text file or a list:

with open("test.txt") as f:
    content = f.readlines()
    str = ""
    for i in xrange(1,len(content)+1):
        str += content[i-1].strip()
        if i % 2 == 0:
            print str
            str = ""

or

with open("test.txt") as f:
    content = f.readlines()
    for i in xrange(1, len(content)+1):
        if i % 2 == 0: print content[i-2].strip() + content[i-1].strip()

Upvotes: 3

thomas
thomas

Reputation: 327

I hope it helps:

import itertools
a =["fname=xxx", "uname=yyy", "fname=zzz", "uname=ppp"]
res = ''
for i in itertools.islice(a, 0, len(a), 2), itertools.islice(a, 1, len(a), 2):
    res += ' '.join(i)
    res += '\n'

print(res)

output:

fname=xxx fname=zzz

uname=yyy uname=ppp

Upvotes: 0

Related Questions