如何在python中的特定行将txt文件注入/插入另一个txt文件

时间:2019-05-27 19:24:48

标签: python text-files

这是我使用Python遇到的一个快速问题。这是我的问题:我尝试在特定行的其他txt文件中注入一个txt文件。这是我尝试过的:

# Modify TXT File
with open("avengers.txt", "w") as file1, open("guardians.txt", 'r') as file2:

    for line in file1:
        print line
        if line == 'Blackwidow':
            for line2 in file2:
                file1.write(line2)

但这给了我一些奇怪的东西(很多中断线)

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow

The story is great
About about the movies :
....
....

guardians.txt

Groot
Rocket
Star Lord
Gamora
Drax

-----结果----

我想做的只是:

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow
Groot <---------------- Insert text here
Rocket
Star Lord
Gamora
Drax

The story is great
About about the movies :
....
....

非常感谢您的帮助

2 个答案:

答案 0 :(得分:2)

--http1.0

答案 1 :(得分:2)

使用'readlines'方法,您可以将文本变成列表对象。然后,找到字符串的索引,在其后放置文本:

with open("avengers.txt", "r+") as file1, open("guardians.txt", 'r') as file2:
    file_new = file1.readlines()
    file1.seek(0)
    bw_index = file_new.index('Blackwidow\n')
    file_new = file_new[:bw_index+1] + file2.readlines() + file_new[bw_index+1 :]
    file1.write(''.join(file_new))