Python

[Python] os listdir()과 scandir()(st_atime, st_mtime, st_ctime)

balabala 2023. 5. 14. 12:09
728x90
SMALL

os.listdir()


  os.listdir() : 'os' 모듈에서 제공하는 함수로 디렉토리 내의 파일 및 디렉토리 목록을 반환하는 함수이다. 간단하고 빠르게 디렉토리 내의 모든 파일과 디렉토리를 가져올 수 있으며, 각 항목은 문자열 형태로 반환된다.
import os

print(os.getcwd())          # os.getcwd() : 현재 작업 디렉토리 경로를 반환
os.chdir('D:\\test')        # os.chdir('변경될 디렉토리 경로') : 현재 작업 디렉토리를 경로를 변경

dir_list = os.listdir()     # os.listdir() : 지정된 디렉토리에 있는 파일 및 디렉토리의 리스트를 반환
# os.path.isdir() : 인자로 전달된 경로가 디렉토리인지 확인
# os.path.isfile() : 인자로 전달된 경로가 파일인지 확인
for d in dir_list:
    print(d, os.path.isdir(d), os.path.isfile(d))

 


os.scandir()


  os.scandir() : 디렉토리 내의 파일 및 디렉토리 목록과 함께 각 항목의 상세한 정보를 반환하는 함수이다. os.DirEntry 객체를 반환하며,  객체 안에 파일 및 디렉토리의 이름, 경로, 크기, 생성 및 수정 시간 등의 속성 정보를 제공한다. 또한 객체를 사용하여 파일 및 디렉토리를 직접 조작할 수도 있다.
import os
import datetime

dir_list = os.scandir()     # os.scandir() : 지정된 디렉토리의 파일 및 디렉토리 목록을 반환하는 함수(os.DirEntry 객체 반환)
print(dir_list)
for file in dir_list:
    print(file, file.name, file.is_dir())
    # st_size : 파일크기(bytes)
    # st_atime(Access Time) : 파일이 마지막으로 읽혔거나 실행되었던 시간
    # st_mtime(Modified Time) : 파일이 마지막으로 수정된 시간
    # st_ctime(Change Time) : 파일이 마지막으로 변경된 시간
    print(file.stat())
    # 1970년 1월 1일 00:00:00 UTC부터 현재까지 경과된 시간을 초 단위로 나타낸 값(년-월-일 시간)
    print(datetime.datetime.fromtimestamp(file.stat().st_ctime))
SMALL

os.listdir() 과 os.scandir()의 차이점


  os.listdir()는 간단하게 파일 및 디렉토리 목록만 가져와야 할 경우에 적합하며, os.scandir()은 상세한 파일 및 디렉토리 정보가 필요할 때 사용하는 것이 좋다. 또한 os.scandir()이 더 많은 시스템 리소스를 사용하기 때문에 대량의 파일 및 디렉토리를 처리 할 때는 주의해야 한다.

 


예제


1. 사용자 입력으로 경로(path)를 받는다.
2. 해당 경로에 있는 디렉토리 및 파일의 이름과 개수를 출력한다.
3. 해당 경로에 있는 파일 중 이름 'test'가 들어간 파일들만 다시 이름과 개수를 출력한다.
import os

path = input('path:')   # 사용자 입력
os.chdir(path)          # 경로 이동

file_list=[]            # 파일 리스트
dir_list=[]             # 디렉토리 리스트
for file in os.scandir():
    if file.is_dir():       # 디렉토리
        dir_list.append(file.name)
    else:                   # 파일
        file_list.append(file.name)
print(f'디렉토리 개수 : {len(dir_list)}, 디렉토리명 : {dir_list}')
print(f'파일 개수 : {len(file_list)}, 파일명 : {file_list}')

test_list = []                  # 파일 이름에 'test' 글자가 들어간 파일 리스트

for name in file_list:
    if 'test' in name.lower():  # 대소문자 구분 없이 test가 들어가면 리스트에 추가
        test_list.append(name)

print(f'test가 들어간 파일 개수 : {len(test_list)}, 파일명 : {test_list}')
728x90
LIST