Python os 모듈(listdir, scandir)

LshDevLog·2026년 2월 15일

python

목록 보기
1/16
post-thumbnail

파이썬 공부 시작해보려함
os모듈에서 listdir와 scandir만 간단하게 알아봄

listdir

import os

path = '.'

print(os.listdir(path))
['data', 'hello.py', 'main.py']

파일, 폴더 리스트를 리턴함


import os

path = '.'

for name in os.listdir(path):
    full_path = os.path.join(path, name)

    if os.path.isfile(full_path):
        print(f'{name} is file')
    elif os.path.isdir(full_path):
        print(f'{name} is directory')

listdir는 이름만 가지기 때문에 파일인지 폴더인지 구분할때 os.path.isfile(), os.path.isdir()를 사용해야함
이러한 방식은 성능면에서 봤을때 그다지 좋은 방법이 아님

각 name마다 isfile(), isdir()을 통해 파일인지 폴더인지 정보가 담겨있는 파일의 metadata를 확인하기 위해 stat 시스템콜을 수행할 수 있기 때문임


scandir

import os

path = '.'

for entry in os.scandir(path):

    if entry.is_file():
        print(f'file name: {entry.name}')
    elif entry.is_dir():
        print(f'dir name: {entry.name}')
dir name: data
file name: hello.py
file name: main.py

scandir의 경우 iterator를 반환하며 각 DirEntry 객체가 처음부터 name, path, is_file(), is_dir() 등의 메서드를 가지고 있어 추가적인 stat 시스템콜을 줄일 수 있기에 성능상 유리

정리하면

listdir: 이름만 받은 뒤 파일마다 다시 OS에 타입 질문
scandir: 처음 받을때 이름과 타입을 같이 받음


추가 정리

syscall

User Space(여기선 Python)에서 Kernel Space(OS)로 요청을 보내는 것
OS kernel의 기능을 호출하기 위한 인터페이스


stat

파일의 metadata를 조회하기 위해 OS커널에 요청하는 syscall

import os

info = os.stat('hello.py')

print(info)
os.stat_result(st_mode=33206, st_ino=9288674232106671, st_dev=16726944052616548876, st_nlink=1, st_uid=0, st_gid=0, st_size=21, st_atime=1771158477, st_mtime=1771158477, st_ctime=1771158471)

python에서는 os.stat()을 통해 사용


iterator

값을 하나씩 순차적으로 반환하는 객체

iterator = iter([1,2,3])

for i in iterator:
    print(i)
1
2
3
iterator = iter([1,2,3])

print(next(iterator))
print(next(iterator))
print(next(iterator))
1
2
3

iter()로 생성하고 next()로 순차적으로 반환


0개의 댓글