dev/기타

특정 코드 존재시 아래의 코드 추가하는 파이썬 코드

jeongsu 2023. 8. 9. 18:00
import os
import sys

# 찾을 문자열
search_text = 'AddGridColumn("PRODUCTSPECNAME'
root_dir = "./"
# 현재 디렉토리에서 모든 폴더 탐색
for root, dirs, files in os.walk(root_dir,topdown=False):
    # 모든 파일 탐색
    for file in files:
        # 파일 열기
        if file == 'python.py':
            continue
        elif not file.endswith('.cs'):
            continue
        elif file.endswith('Designer.cs'):
            continue

        with open(os.path.join(root, file), "r",encoding='UTF-8') as f:
            # 파일의 내용을 한줄씩읽기
            content = f.readlines()
            # contents 초기화
            contents =""
            is_search_text = False
            for x in content:
                # 찾을 문자열이 있는지 확인
                contents= contents + x
                if search_text in x:
                    target = x
                    target = target.replace("PRODUCTSPECNAME","PRODUCTSPECVERSION")
                    target = target.replace('LanguageService.Instance.GetLabel("ProductSpecName")','LanguageService.Instance.GetLabel("ProductSpecVersion")')
                    target = target.replace('LanguageService.Instance.GetLabel("PartName")','LanguageService.Instance.GetLabel("ProductSpecVersion")')
                    target = target.replace('LanguageService.Instance.GetLabel("Product")','LanguageService.Instance.GetLabel("ProductSpecVersion")')
                    contents = contents + target
                    is_search_text = True

            # 파일에 내용을 쓰기
            if is_search_text == True :
                with open(os.path.join(root, file), "w",encoding='UTF-8') as f:
                    f.write(contents)
                with open(os.path.join(root_dir, 'modify.txt'), "a",encoding='UTF-8') as f:
                    f.write(os.path.join(root, file)+'\n')