IT’s Portfolio

[Python] 하위 디렉터리 검색 (sys 라이브러리 응용) 본문

Development Study/Python

[Python] 하위 디렉터리 검색 (sys 라이브러리 응용)

f1r3_r41n 2020. 6. 10. 15:54
728x90
반응형

** 점프 투 파이썬 **

 

Q. 입력받은 특정 디렉터리부터 시작해서 하위 모든 파일 중 입력받은 확장자 파일만 출력해주는 스크립트를 만드려면 어떻게 해야할까?

 

=> 전날 간단한 메모장 스크립트에서 배운 sys 라이브러리를 응용해서 만들어보자.

https://it-neicebee.tistory.com/94

 

[Python] 간단한 메모장 스크립트 만들기

** 점프 투 파이썬 ** ① 메모 추가하기 ② 메모 읽기 ③ 메모 삭제하기 import sys # 명령어 체크 메서드 def check_command(): try: ''' 만약 python memo.py -a hello world 라는 명령어를 입력했을 때 sys.arg..

it-neicebee.tistory.com

 

import os
import sys

# 디렉터리 검색 시 확장자를 가진 파일이 없을 때를 체크할 리스트
check_file = []

def rt_option_command():
    command = sys.argv
    try:
        option = command[1]

        if option == '-s':
            check_command(command)
        else:
            print("Command Error!")
    except:
        print("Command Error!")

def check_command(command):
    try:
        dirname = command[2]
        ext = command[3]

        search(dirname, ext)
        check_list_checkfile(dirname, ext)
    except:
        print("Command Error!")

def search(dirname, ext):
    try:
        '''
        os.listdir : 해당 디렉터리에 있는 파일들의 리스트를 구함.
        os.listdir은 파일 이름만 포함되어 있기 때문에 인자값으로 받는 dirname을 붙여줘야 한다.
        os.listdir 메서드를 수행 시 권한이 없는 디렉터리에 접근하면 Permission Error가 뜬다. 그래서 try, except 문을 사용한다.
        
        디렉터리와 파일 이름을 이어주는 os.path.join 함수를 사용해 전체 경로를 구할 수 있다.
        '''
        filenames = os.listdir(dirname)

        for filename in filenames:
            full_filename = os.path.join(dirname, filename)
            '''
            os.path.isdir : 해당 인자가 디렉터리인지 파일인지 구별하는 메서드. bool 자료형을 리턴한다.
            
            해당 디렉터리의 파일이 디렉터리일 경우 다시 search 함수를 호출해나가면 해당 디렉터리의 하위 파일을 다시 검색하기 때문에 모든 파일을 검색할 수 있다.
            => 재귀호출 : 자기 자신을 다시 호출하는 프로그래밍 기법.
            '''
            if os.path.isdir(full_filename):
                search(full_filename, ext)
            else:
                '''
                os.path.splitext : 파일 이름을 확장자 기준으로 split하는 메서드
                따라서 [-1]로 문자열 인덱싱을 하면 확장자만 남게된다.
                '''
                check_ext = os.path.splitext(full_filename)[-1]
                if check_ext == ext:
                    check_file.append(full_filename)
                    print(full_filename)
    except PermissionError:
        pass

def check_list_checkfile(dirname, ext):
    # 리스트의 길이가 0이면 출력함.
    if len(check_file) == 0:
        print(dirname + "의 하위 디렉터리에 " + ext + " 확장자를 가진 파일이 없습니다.")

if __name__ == '__main__':
    rt_option_command()

'''
os.walk : 시작 디렉터리부터 시작하여 그 하위 모든 디렉터리를 차례대로 방문하는 메서드.
'''

 

실행

D 드라이브의 디렉터리들에서 .exe 확장자를 가진 파일들이 출력된다.

 

728x90
반응형
Comments