Neal
Neal

Reputation: 25

How to combine every line with it's subsequent line in a text file

I have a text file z.txt. It looks like this:

alcoholic
alert
algebra
alibi
blablabla
...

How can I use python to make each line look like this (combined with it's subsequent line):

alcoholic alert
alert algebra
algebra alibi
alibi blablabla
blablabla ...

The incomplete code I have looks like this:

with open('z.txt','r') as inF:
    for line in inF:
        line =

Any help would be appreciated. Thanks.

Upvotes: 1

Views: 39

Answers (2)

hygull
hygull

Reputation: 8740

I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.

Let suppose your z.txt has the following contents in it.

z.txt

alcoholic
alert
algebra
alibi
blablabla

Now, you can try like this.

construct.py

output_lines = []

with open("z.txt") as f:
    lines = f.readlines()
    l =  len(lines)

    if l <= 1:
        if l == 1:
            output_lines = lines[0]
    else:
        # strip() is to remove `\n` from end of `lines[index]`
        output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

print(output_lines)
# ['alcoholic alert\n', 'alert algebra\n', 'algebra alibi\n', 'alibi blablabla']

# If you wish to save it in a file named `z_out.txt`
with open("z_out.txt", "w") as f:
    f.writelines(output_lines)

z_out.txt

alcoholic alert
alert algebra
algebra alibi
alibi blablabla

Upvotes: 1

kerwei
kerwei

Reputation: 1842

Here's a possibility using list comprehension, giving you the output in the form of a list.

with open('z.txt','r') as f: 
    wordlist = f.read().split('\n')

>>>wordlist
['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

>>>combineduo
['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']

Upvotes: 1

Related Questions