Python/45가지 파이썬 기초문법 예제

파이썬 (42) 파일 확장자 체크

monstro 2025. 6. 4. 00:31
728x90
반응형

이번 포스트에서는 폴더에 저장된 파일들에서 특정한 확장자를 지닌 파일들만을 체크하는 예제를 알아본다

 

위와 같은 폴더에서 .py 확장자와 .png 확장자를 지닌 파일들을 모아서 출력한다

 

1) os 모듈만을 사용

import os

def defineFileExtensionName(filepath):
    pngList = []
    pyList = []

    if os.path.exists(filepath):
        for file in os.listdir(filepath):
            if ".py" in file or ".PY" in file:
                pyList.append(file)
            elif ".png" in file or ".PNG" in file:
                pngList.append(file)

    print(f"PNG file info : {pngList} Count : {len(pngList)}")
    print(f"Py file info : {pyList} Count : {len(pyList)}")
    
defineFileExtensionName("TargetFolder/")

 

os 모듈의 listdir 함수를 사용하면 경로를 넘겨주고 해당 경로에 존재하는 파일들리스트 형태로 반환한다

이때 파일의 이름을 문자열로 저장하므로 파일 안에서 .py 또는 .png를 찾아원하는 결과를 추출할 수 있다

실행 결과는 다음과 같다

 

2) glob 모듈 추가로 사용

import glob

def defineFileExtensionName2(filepath):
    pngList = []
    pyList = []

    if os.path.exists(filepath):
        pyList = glob.glob1(filepath , '*.py')
        pngList = glob.glob1(filepath , '*.png')

    print(f"PNG file info : {pngList} Count : {len(pngList)}")
    print(f"Py file info : {pyList} Count : {len(pyList)}")

defineFileExtensionName2("TargetFolder/")

 

glob 모듈의 glob1 함수를 사용하면 경로와 확장자를 같이 넘겨주어

경로에 존재하는 파일 중에서 넘겨준 확장자에 해당하는 파일만 리스트 형태로 반환한다

최종 실행 결과는 다음과 같다

728x90
반응형