인공지능 공부/남박사의 파이썬 실전

(인프런) 10. 파이썬 실전 파일 인코딩 변경 프로그램 만들기

앨런튜링_ 2021. 5. 29. 17:25
import os
## pip install chardet 해줘야함.
from chardet import detect
import argparse ##경로를 한번 자동으로 설정해보자
os.system("cls")


##print(os.listdir(path)) ##안까지 들어가지 못해서 재귀함수 사용 
def search_dir(dirname):
    result_list = []
    filenames = os.listdir(dirname)


    for filename in filenames:
        full_path = os.path.join(dirname, filename) ##경로를 더해주는 os.path.join
        if os.path.isdir(full_path):
          result_list.extend(search_dir(full_path)) ##폴더가 있으면 계속 들어감 ##그런데 serch_dir이
                                                      ##리스트를 반환하기 때문에 extend 해줘야함
        else:
            result_list.append(full_path)
    return result_list

def get_encoding_type(filepath):
    with open(filepath,"rb") as f:
        rawdata = f.read()

    codec = detect(rawdata)
    return codec["encoding"]


INCLUDE_EXT_LIST = [".txt", ".smi"]


parse = argparse.ArgumentParser()
parse.add_argument("-f", type=str)
parse.add_argument("-e", nargs="+") ##열거되는 텍스트를 리스트로 넘겨줌
args = parse.parse_args()##형식에 맞게 다 저장함


if args.f is not None:
    path = args.f ##역슬레쉬 하나면 탭이기 때문에 두개해줘야함
    filelists = search_dir(path)

    if args.e is not None: #사용자가 값을 입력한것 확장자!
        if len(args.e) >0:
            # for e in args.e:
            #     INCLUDE_EXT_LIST = [] ##초기화
            #     if e[0:1] == ".":
            #          INCLUDE_EXT_LIST.append(e)
            #     else:
            #         INCLUDE_EXT_LIST = [".", e]    
            ##위에줄을 한줄에 쓰기 ! 
            INCLUDE_EXT_LIST = [e.lower() if e[0:1] == "." else ".{}".format(e.lower()) for e in args.e]
    #C:\\test\\aaa.txt,
    ##확장자를 분리하는 작업 시작
    for file in filelists:
        filename, ext = os.path.splitext(file) ##확장자만 분리해주는 함수가 있음
        tempfile = filename+"_tmp" +ext
        if ext.lower() in INCLUDE_EXT_LIST:
            encoding = get_encoding_type(file)
            if encoding.lower().find("utf") <0:
                try: #혹시 오류날 수 있기에 try문으로 해준다
                    with open(file, "r") as read, open(tempfile, "w", encoding="utf-8") as write:
                        write.write(read.read())
                    os.unlink(file)#원본파일 삭제
                    os.rename(tempfile,file)#임시파일명을 원본파일명으로 바꿔줌
                    print("{}이 저장 되었습니다.".format(file))
                except:
                    pass
                finally:
                    if os.path.exists(tempfile):
                        os.unlink(tempfile)