简体   繁体   中英

Replace a line with a pattern

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

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.

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

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