4

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)
ppsn
  • 39
  • 5
  • 4
    given your `lineList`, you can use the following: `[" ".join([lineList[i], lineList[i+1]]) for i in range(0, len(lineList), 2)]`. or: `list(" ".join(l) for l in zip(lines[:-1:2], lines[1:None:2]))` – sim Jan 07 '21 at 20:09
  • 1
    This is an excellent answer. Concise and Pythonic. – whege Jan 07 '21 at 20:12
  • Is it assumed the file has an even number of lines? – ssp Jan 07 '21 at 20:16
  • @Moosefeather, OP will need to check len(lineList) and if not even, then join the last line separately. This is for sim's response – Joe Ferndz Jan 07 '21 at 20:25
  • The bulk of the question is a duplicate of https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python. I'm only reluctant to close as a duplicate because one also has to open the file and use that iterator (which is a trivial complication, to be honest). – Andras Deak -- Слава Україні Jan 07 '21 at 21:39

1 Answers1

3

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.

ssp
  • 1,666
  • 11
  • 15