Search code examples
pythonparsingtextmarkdowntxt

Move text from one file to another using specific positions python


I want to move specific parts of a text file (using special strings, e.g. #) to another file. Like: Similar Solution. My problem is that I want also to specify the destination into the output file.

E.g.

I have a text file in which a piece start with #1 and after some lines ends with #2

FIle1.txt

hello
a
b
#1
a
b
#2
c

I have another file (not a txt but a markdown) like this:

File2

header
a
b
#1

#2 
d

I want to move the text inside the special character (#1 and #2) from the first file into the second one. So as result:

File2

header
a
b
#1
a
b
#2 
d

Solution

  • IIUC, you want:

    with open("file1.txt") as f:
        f1 = [line.strip() for line in f]
        
    with open("file2.md") as f:
        f2 = [line.strip() for line in f]
    
    output = f2[:f2.index("#1")]+f1[f1.index("#1"):f1.index("#2")]+f2[f2.index("#2"):]
    with open("output.md", "w") as f:
        f.write("\n".join(output))