ppsn
ppsn

Reputation: 41

How to merge every two lines of a text file into a single string in Python?

I want to merge every two lines of a text file into a single string, with all the strings grouped into a single list. Example of text file:

This is an example text file
containing multiple lines
of text, with each line
containing words made out of letters

I want the code to create strings like this:

This is an example text file containing multiple lines
of text, with each line containing words made out of letters

I have tried some solutions but they were for Python 2, but i am working with Python 3.9

This is what code i currently have (i wrote it myself)

with open(filePath) as text: # filePath is a variable asking for input by user, the user is required to type the file path of the .txt.file
lineCount = 0
firstLine = ""
secondLine = ""
lineList = []
finalResultList = []



for line in text: # Appends all the lines of the file
    lineList.append(line)

for i in lineList: # Merges 2 lines at a time into a single one
    if lineCount == 0:
        firstLine = i
        lineCount += 1
    elif lineCount == 1:
        secondLine = i
        lineCount = 0
        finalResult = str(str(firstLine) + " " + str(secondLine))
        finalResultList.append(finalResult)

Upvotes: 4

Views: 1966

Answers (1)

ssp
ssp

Reputation: 1710

Based on @sim 's comment:

with open('text.txt', 'r') as f:
    lines = f.read().splitlines()

res = [' '.join(lines[i: i+2]) for i in range(0, len(lines), 2)]

Note this works with an odd number of lines too.

Upvotes: 3

Related Questions