Home > Software engineering >  Move text from one file to another using specific positions python
Move text from one file to another using specific positions python

Time:10-26

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

CodePudding user response:

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

CodePudding user response:

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