简体   繁体   中英

Move text from one file to another using specific positions python

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

Eg

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

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

I wrote a less pythonic example, which is easier modifiable in case you have more anchor points. It uses a very simple state machine.

to_copy = ""

copy_state = False

with  open("file1.txt") as f:
    for el in f:
        
        # update state. We need to leave copy state before finding end symbol
        if copy_state and "#2" in el: 
            copy_state = False
        
        if copy_state:
            to_copy += el
        
        # update state. We need to enter copy state after finding end symbol
        if not copy_state and "#1" in el:
            copy_state = True
#debug       
print(to_copy)

output = ""

with open("file2.txt") as fc:
    with open("file_merge.txt","w") as fm:
                
        for el in fc:
            
            #copy file 2 into file_merge
            output += el    
        
            #pretty much the same logic
            
            # update state. We need to leave copy state before finding end symbol
            if copy_state and "#2" in el: 
                copy_state = False
            
                
            
            # update state. We need to enter copy state after finding end symbol
            if not copy_state and "#1" in el:
                copy_state = True
            
                # if detected start copy, attach what you want to copy from file1
                output += to_copy
                
                
        fm.write(output)
    
#debug    
print(output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM