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:

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. or we can say now i want to keep the line as a commented line in my file. I need help in this i have tried many ways but not able to find

Lamanus
  • 12,898
  • 4
  • 21
  • 47
  • Your answer seems to want to work on lists of patterns and replacements, is that correct? can you show an example of how `replacetext()` is called and add potentially add the missing code to `modify_user_code()`? – JonSG Jun 30 '23 at 15:05
  • If you are looking to include the capture in the call to `sub()` check out https://stackoverflow.com/questions/7191209/re-sub-replace-with-matched-content – JonSG Jun 30 '23 at 15:08
  • @JonSG replace text is called in modify_user_code() as if '.py' == file_ext: replacetext([regex_a], [subst_a], file_edit) – abhishek jain Jun 30 '23 at 15:54
  • i want to just add # in the line which found using regex. instead of replacing with "" – abhishek jain Jun 30 '23 at 15:55
  • 1
    it worked with this r'#\g<0>' – abhishek jain Jun 30 '23 at 16:00

0 Answers0