如何在Python中合并文本文件中的行?

问题描述 投票:0回答:1

我需要帮助将更多行组合到一个文本文件中,例如:我的文本文件看起来像这样:

1号线

2号线

3号线

4号线

5号线

我想将 Line more 合并到第 1 行,然后打印文本文件的内容,使其看起来像这样:

1号线

2号线1号线

3号线1号线

4号线1号线

5号线 1号线

我知道如何使用以下方式打印文件的内容:Print file.read()

我只是不明白如何组合前几行。

我希望你能帮助我解决我的问题

python python-2.7
1个回答
0
投票

你可以试试

with open("text_file.txt") as file: #replace file name with your file
    firt_line=""
    for i,line in enumerate(file):
        if i==0: #get first line
            firt_line=line.rstrip('\n')
            print(firt_line)
        else: # add first line to other lines.
            print(line.rstrip('\n')+firt_line)

输出

Line 1
Line 2Line 1
Line 3Line 1
Line 4Line 1
Line 5Line 1
© www.soinside.com 2019 - 2024. All rights reserved.