MagicaNexus
MagicaNexus

Reputation: 312

How to inject/insert a txt file into another txt file at a specific line in Python

This is a quick problem I have with Python. This is my problem here : I try to inject a txt file inside an other txt file at a specific line. This is what I tried:

# 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)

But it gives me something weird (A lot of break lines)

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

----- RESULT ----

What I want to do is just :

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 :
....
....

Thank you very much for your help

Upvotes: 2

Views: 621

Answers (2)

Masoud
Masoud

Reputation: 1280

Using 'readlines' method, you can turn the text into a list object. Then, find the index of the string, place the text after it:

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))

Upvotes: 2

Olvin Roght
Olvin Roght

Reputation: 7812

with open("avengers.txt", "r+") as f1, open("guardians.txt") as f2:
    line = f1.readline()
    while line:
        if line.startswith("Blackwidow"):
            offset = f1.tell()
            rest_of_file = f1.readlines()
            f1.seek(offset)
            f1.writelines(f2.readlines())
            f1.writelines(rest_of_file)
            break
        line = f1.readline()

Upvotes: 2

Related Questions