Home > Enterprise >  Replace a line with a pattern
Replace a line with a pattern

Time:02-19

I am trying to replace a line when a pattern (only one pattern I have in that file) found with the below code, but it replaced whole content of the file. Could you please advise or any better way with pathlib ?

import datetime

def insert_timestamp():
    """ To Update the current date in DNS files """
    pattern = '; serial number'
    current_day = datetime.datetime.today().strftime('%Y%m%d')
    subst = "\t"   str(current_day)   "01"   " ; "   pattern

    print(current_day)

   
    with open(lab_net_file, "w ") as file:
        for line in file:
            file.write(line if pattern not in line else line.replace(pattern, subst))

lab_net_file = '/Users/kams/nameserver/10_15'
insert_timestamp()

CodePudding user response:

What you would want to do is read the file, replace the pattern, and write to it again like this:

with open(lab_net_file, "r") as file:
    read = file.read()

read = read.replace(pattern, subst)


with open(lab_net_file, "w") as file:
    file.write(read)

The reason that you don't need to use if/else is because if there is no pattern inside read, then .replace won't do anything, and you don't need to worry about it. If pattern is inside read, then .replace will replace it throughout the entire string.

CodePudding user response:

I am able to get the output I wanted with this block of code.

    def insert_timestamp(self):
        """ To Update the current date in DNS files """
        pattern = re.compile(r'\s[0-9]*\s;\sserial number')
        current_day = datetime.datetime.today().strftime('%Y%m%d')
        subst = "\t"   str(current_day)   "01"   " ; "   'serial number'


        with open(lab_net_file, "r") as file:
            reading_file = file.read()
            pattern = pattern.search(reading_file).group()

        reading_file = reading_file.replace(pattern, subst)

        with open(lab_net_file, "w") as file:
            file.write(reading_file)

Thank you @Timmy

  • Related