Search code examples
pythonpython-3.xfileediting

Edit a File in Python and write the results on a new file but only in specific areas


I want to make a script doing the following:

i have file_ori.txt that its contents are like this ( numbers are just line numbers not actual text )

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a line with lalala text
6 This is test line with random text
7 This is also a line with lalala text
8 end sequence
9 This is test line with random text

What i want to accomplice is a change the word "line" with word "Pine" in the whole file but only pass the changes in the new file between start sequence and end sequence and the result would be this :

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a Pine with lalala text
6 This is test Pine with random text
7 This is also a Pine with lalala text
8 end sequence
9 This is test line with random text

It is crucial in my case that i don't want to split the file prior the replace but only after. I have to work on the full read.

f = open(file_ori.txt, "r")
full_read = f.read()

full_read = full_read.replace('line', 'Pine')

............. I don't know how to continue

f = open(file_ori_edit.txt, 'w')
    f.write(full_read)
    f.close()

Thank you.


Solution

  • This is one approach.

    Ex:

    start = 'start sequence'
    end = 'end sequence'
    parse = False
    result = []
    with open(filename) as infile:
        for line in infile:      #Iterate each line
            line = line.strip()
            if start == line:    #check for start sequence
                parse = True
            if end == line:      #check for end sequence
                parse = False
    
            if parse:   #Replace ONLY between sequence
                line = line.replace('line', 'Pine')
            result.append(line+"\n")
    
    with open(filename, "w") as outfile:
        outfile.writelines(result)