Python에서는 특정 경로에 있는 디렉토리와 파일의 목록을 조회하는 방법이 여러 가지 있습니다. 이 글에서는 os.listdir(), os.path 모듈, filter(), 정규 표현식, 그리고 os.walk()까지 다양한 방법을 예제 코드와 함께 살펴보겠습니다.
1. 디렉토리 내 파일 목록 조회하기
특정 경로에 있는 모든 파일이나 디렉토리를 가져오는 가장 간단한 방법 중 하나는 os.listdir() 메서드를 사용하는 것입니다.
import os
for x in os.listdir('.'):
print(x)
실행 결과
.pytest_cache
4forces.json
annotation1.py
asyncWrite.txt
attribute_access.py
background_process.py
background_process2.py
BeautifulSoup_script1.py
bottle_exampl1.py
bottole_test1.py
build
built-in_funct.py
callable_objects1.py
cars.csv
classes_instance.py
class_attributes.py
class_attributes1.py
code_gmplot.py
config.py
data1.json
datafile.txt
……
위 코드는 현재 작업 디렉토리(current working directory)에 있는 파일과 디렉토리 목록을 출력합니다. 만약 특정 디렉토리의 파일과 디렉토리를 조회하고 싶다면, 절대 경로(absolute pathname)를 인자로 전달하면 됩니다.
import os
for x in os.listdir(r'C:\Python\Python361\selenium'):
print(x)
실행 결과
geckodriver.log
test1.py
webdriver
결과는 아래 폴더 구조와 동일하게 나타납니다.

2. 파일, 디렉토리, 링크 구분하기
위 출력 결과만으로는 해당 항목이 파일인지, 디렉토리인지, 아니면 링크인지 알 수 없습니다. 항목의 유형을 확인하려면 os.path.isfile(), os.path.isdir(), os.path.islink() 함수를 활용할 수 있습니다.
import os
for x in os.listdir('.'):
if os.path.isfile(x): print('file-', x)
elif os.path.isdir(x): print('directory-', x)
elif os.path.islink(x): print('link-', x)
else: print('---', x)
실행 결과
directory- .pytest_cache
file- 4forces.json
file- annotation1.py
file- asyncWrite.txt
file- attribute_access.py
file- background_process.py
file- background_process2.py
file- BeautifulSoup_script1.py
file- bottle_exampl1.py
file- bottole_test1.py
directory- build
file- built-in_funct.py
file- callable_objects1.py
file- cars.csv
file- classes_instance.py
file- class_attributes.py
file- class_attributes1.py
file- code_gmplot.py
file- config.py
file- data1.json
file- datafile.txt
directory- dist
directory- django
directory- DLLs
directory- Doc
file- dynamic_array_implementation.py
3. filter()를 활용한 한 줄 코드
filter() 함수를 사용하면 특정 경로에서 파일만 골라내는 작업을 한 줄로 처리할 수 있습니다.
파일만 추출하기
list(filter(lambda x: os.path.isfile(x), os.listdir('.')))디렉토리만 추출하기
list(filter(lambda x: os.path.isdir(x), os.listdir('.')))실행 결과
['.pytest_cache', 'build', 'dist', 'django', 'DLLs', 'Doc', 'etc', 'gmplot', 'gmplot-1.2.0', 'gmplot.egg-info', 'include', 'Lib', 'libs', 'networkP', 'Scripts', 'selenium', 'share', 'tcl', 'Tools', '__pycache__']
4. 특정 확장자의 파일 찾기
아래는 디렉토리에서 텍스트 파일(.txt)만 찾아내는 한 줄 코드입니다. 단, 이 방법은 하위 디렉토리까지 탐색하지 않고 지정된 디렉토리 내에서 일치하는 항목만 반환한다는 점에 유의하세요.
list(filter(lambda x: x.endswith('.txt'), os.listdir('.')))실행 결과
['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt']
위 코드는 리스트 컴프리헨션(list comprehension)으로도 작성할 수 있습니다.
>>> list(x for x in os.listdir('.') if x.endswith('.txt'))
['asyncWrite.txt', 'datafile.txt', 'exercise.txt', 'finally.txt', 'LICENSE.txt', 'NEWS.txt', 'out.txt', 'test.txt', 'test1.txt', 'test2.txt']정규 표현식 활용하기
또 다른 방법으로는 정규 표현식(regular expression)을 사용하는 것이 있습니다. 아래 예제는 .txt 또는 .py 확장자를 가진 항목을 필터링합니다.
import re
fx = re.compile(r'\.(txt|py)')
print(list(filter(fx.search, os.listdir('.'))))
5. os.walk()를 사용한 재귀적 탐색
os.walk() 메서드는 디렉토리 트리 전체를 순회하면서 파일명을 생성(generator)합니다. 하위 디렉토리까지 모두 탐색해야 할 때 유용합니다.
import os
for root, dirs, files in os.walk(r'C:\Python\Python361\selenium'):
for filename in files:
print(filename)
실행 결과
geckodriver.log
test1.py
x_ignore_nofocus.so
x_ignore_nofocus.so
getAttribute.js
isDisplayed.js
마무리
정리하면, os.listdir()은 단일 디렉토리의 항목을 빠르게 확인할 때, os.path 계열 함수는 항목의 유형을 판별할 때, filter()나 리스트 컴프리헨션은 원하는 조건의 파일만 추출할 때, 그리고 os.walk()는 하위 디렉토리까지 재귀적으로 탐색할 때 각각 유용하게 사용할 수 있습니다. 상황에 맞는 방법을 선택하여 파일 시스템 작업을 더욱 효율적으로 처리해 보세요.