파이썬 폴더 순회 os.scandir. python

다이얼로그에서 폴더 선택 후 작업하는 일반적인 패턴 구현 소스.


import os
import tkinter
import tkinter.filedialog
import tkinter.messagebox


def select_folder():
    path = tkinter.filedialog.askdirectory()
    return path


def work_file(src_path):
    try:
        path, name = os.path.split(src_path)

    except Exception as e:
        tkinter.messagebox.showinfo("Exception!", e)


def work_folder(folder_path, is_sub):
    try:
        with os.scandir(folder_path) as it:
            for entry in it:
                if entry.is_file():
                    work_file(entry.path)
                elif is_sub and entry.is_dir():
                    work_folder(entry.path, is_sub)

    except Exception as e:
        tkinter.messagebox.showinfo("Exception!", e)


if __name__ == "__main__":

    try:
        work_path = select_folder()
        work_folder(work_path, True)
        os.system("pause")

    except Exception as e:
        tkinter.messagebox.showinfo("Exception!", e)
        # with open('Log.txt', 'a', encoding='utf-8', errors='ignore') as f:
        #    f.write(e)



* 참고.
https://docs.python.org/ko/3/library/os.html?highlight=scandir#os.scandir

댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore

플러터(flutter) 개발 참고 사이트들.