728x90
반응형
이번 포스트에서는 폴더에 존재하는 파일들을 가져오되, 파일안에 파일이 존재하는 재귀적 구조에서 가져온다

위와 같은 폴더 구조에서 txt 파일과 png 파일을 가져와 배열에 저장하고 개수를 반환하면 된다
1) os 모듈의 walk 메서드 사용
import os
def findFilesWithSubFolder(filepath):
txtList = []
pngList = []
if os.path.exists(filepath):
for root, subfolder, files in os.walk(filepath):
for file in files:
if ".txt" in file or ".TXT" in file:
txtList.append(file)
elif ".png" in file or ".PNG" in file:
pngList.append(file)
print(f"TXT file info : {txtList} Count : {len(txtList)}")
print(f"PNG file info : {pngList} Count : {len(pngList)}")
findFilesWithSubFolder("TargetFolder_02")
os 모듈의 walk 메서드는 폴더를 재귀적으로 탐색할 수 있는 함수이다
사용하면 루트 디렉토리 / 하위 폴더 / 모든 파일로 구성되어 있는 시퀀스를 반환하는데,
이 중에서 파일을 순회하면서 파일의 확장자를 판단하여 이를 저장하고 반환한다
최종 실행 결과는 다음과 같다

2) glob 모듈의 glob 메서드 사용
import glob
def findFilesWithSubFolder2(filepath):
txtList = []
pngList = []
if os.path.exists(filepath):
txtList = [os.path.basename(filepath) for filepath in glob.glob(f"{filepath}/**/*.txt", recursive=True)
if os.path.isfile(filepath)]
pngList = [os.path.basename(filepath) for filepath in glob.glob(f"{filepath}/**/*.png", recursive=True)
if os.path.isfile(filepath)]
print(f"TXT file info : {txtList} Count : {len(txtList)}")
print(f"PNG file info : {pngList} Count : {len(pngList)}")
findFilesWithSubFolder2("TargetFolder_02")
glob 모듈의 glob 메서드에서 recursive 속성을 True로 설정하면 재귀적으로 파일을 탐색할 수 있다
이때 가져오는 결과값에 경로가 포함되므로 os 모듈의 isfile 함수를 통해 파일만을 가져와서 저장하고 반환한다
최종 실행 결과는 다음과 같다

728x90
반응형
'Python > 45가지 파이썬 기초문법 예제' 카테고리의 다른 글
| 파이썬 (45) 간단 프로젝트 (0) | 2025.06.09 |
|---|---|
| 파이썬 (44) 파일 읽기 & 쓰기 고급 (0) | 2025.06.09 |
| 파이썬 (42) 파일 확장자 체크 (0) | 2025.06.04 |
| 파이썬 (41) 텍스트 파일 필터링 (0) | 2025.06.02 |
| 파이썬 (40) 비밀번호 체크 (0) | 2025.05.31 |