python - 如何在 Python 中将文本文件的每两行合并为一个字符串?

标签 python python-3.x

我想将文本文件的每两行合并为一个字符串,所有的字符串都分组到一个列表中。文本文件示例:

This is an example text file
containing multiple lines
of text, with each line
containing words made out of letters
我希望代码创建这样的字符串:
This is an example text file containing multiple lines
of text, with each line containing words made out of letters
我尝试了一些解决方案,但它们适用于 Python 2,但我正在使用 Python 3.9
这是我目前拥有的代码(我自己写的)
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)

最佳答案

基于@sim 的评论:

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)]
请注意,这也适用于奇数行。

关于python - 如何在 Python 中将文本文件的每两行合并为一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65619175/

相关文章:

python - Beautiful Soup - 列表中所有项目的结果转为 CSV

python - Winreg Python、QueryInfoKey 给出的上次更改的日期/时间不正确?

linux - 如何通过 pip 安装 vowpalwabbit

python-3.x - 合并两个带有条件的 DataFrame 以更新列或追加行

python - 使用 tflearn、tensorflow、numpy 的 Python 聊天机器人出现错误

python - Python DBM 真的很快吗?

python - 使用 matplotlib 绘制 SQL (MariaDB) 中的表值

python - solvePnPRansac 为 rvecs 和 tvecs 返回零值

python - PIL Tkinter 奇怪的错误 : couldn't recognize data in [png] image file

python - 在 python 中解析 json 文件会造成困难