꽃무늬 키보드

[python] 디렉토리 전체 탐색, 특정 파일 필터링 본문

Programming/python

[python] 디렉토리 전체 탐색, 특정 파일 필터링

Katherine Choi 2014. 6. 16. 16:04

특정 디렉토리를 재귀적으로 탐색하여 모든 파일들과 절대경로를 출력

import os
pwd = '탐색할 디렉토리 경로'
for path, dirs, files in os.walk(pwd):
    for file in files:
        print  '탐색파일과 절대경로: ' + os.path.join(path, file)



탐색 시, 특정 디렉토리 제외하기 (예: etc 파일 제외)

for path, dirs, files in os.walk(pwd):
        dirs[:] = [dir for dir in dirs if dir != "etc"]



탐색 시, 특정 파일만 추려내기 (예: 확장자가 .pyc인 파일 추리기)

for path, dirs, files in os.walk(pwd):
        for file in files:
                if os.path.splitext(file)[1].lower() == '.pyc':
                        print 'pyc 파일: ' + file


Comments