0

I have a python file which i am reading and trying to find a pattern using regex once find i am replacing it with empty string like this.

def modify_user_code():
    regex_a = r"^[a-zA-Z]+\.sql\(\"create database if not exists [a-zA-Z0-9\/_]+ location [\'a-zA-Z0-9\/_]+\"\)"
    subst_a = ""

    dir_list = os.listdir(os.path.join(path_root, "tasks"))
    for file_name in dir_list:
        logger.debug(f"dir has {file_name}")
        file_ext = os.path.splitext(file_name)[1]
        file_edit = os.path.join(path_root, 'tasks', file_name)
        logger.info(f"editing {file_edit}")
        if '.py' == file_ext:
        replacetext([regex_a],[subst_a], file_edit)

def replacetext(search_text_arr, replace_text_arr, path_to_file):
    with open(path_to_file, 'r+') as f:
        file = f.read()
        for i in range(len(search_text_arr)):
            logger.debug(f"search={search_text_arr[i]} replace={replace_text_arr[i]}")
            file = re.sub(search_text_arr[i], replace_text_arr[i], file, flags=re.MULTILINE)
        f.seek(0)
        size = f.write(file)
        f.truncate()
    return size

i want to append # at the start of the line instead of removing the line now. and i want to add a new modified line in same file after commenting the original line.. or we can say now i want to keep the line as a commented line in my file and also a new line with modified values. I need help in this i have tried many ways but not able to find

I have:

line:- Hi i am using this db which is quite good.

result:- ""

I Want:

line:- Hi i am using this db which is quite good.

result:-

#Hi i am using this db which is quite good.

Hi i am using this db which is quite bad.

parisni
  • 920
  • 7
  • 20

0 Answers0