원하는 파일을 불러오거나 특정 시점의 파일 정보를 얻기 위해 폴더 내 데이터 파일이 생성된 날짜 또는 수정된 날짜를 확인해야 하는 경우가 있습니다. 이런 경우 사용할 수 있는 메소드 입니다.
OS 모듈
os.path 메소드를 사용하기 위해서는 os 모듈을 import 해야 합니다.
os 모듈은 내장 모듈로 python 설치 시 함께 설치되기 때문에 별도 라이브러리 다운로드가 필요하지 않습니다.
아래와 같이 import로 호출하게 됩니다.
import os
getctime( ) : the time of creation time for the specified path 폴더/파일 생성 날짜
파일의 생성 날짜를 확인하는 코드를 간단히 알아보겠습니다.
파일의 경로는 폴더, 파일 모두 가능합니다.
# 파일 생성 일자
ctime_folder = os.path.getctime('d:/pylife/os') # 폴더
ctime_file = os.path.getctime('d:/pylife/os/getc(m)time.xlsx') # 파일
print('ctime_folder :', ctime_folder)
print('ctime_file :', ctime_file)
위의 코드를 바탕으로 생성한 날짜를 확인하면 아래와 같습니다.
ctime_folder : 1656027723.3067665
ctime_file : 1656027883.956632
소수점을 기준으로 정수에 날짜를 소수에 시분초를 표기하는 형식으로 값이 반환됩니다.
getmtime( ) : the time of last modification of the specified path 폴더/ 파일의 수정 날짜
다음은 파일 수정 날짜를 확인하는 코드입니다.
# 파일 수정 일자
mtime_folder = os.path.getmtime('d:/pylife/os') # 폴더
mtime_file = os.path.getmtime('d:/pylife/os/getc(m)time.xlsx') # 파일
print('mtime_folder :', mtime_folder)
print('mtime_file :', mtime_file)
위의 코드를 바탕으로 수정한 날짜를 확인하면 아래와 같습니다.
mtime_folder : 1656027887.8841386
mtime_file : 1656027883.950647
getatime() : the time of last access of the specified path 폴더/파일의 접근 날짜
다음은 파일 접근 날짜를 확인하는 코드입니다.
# 파일 접근 일자
atime_folder = os.path.getatime('d:/pylife/os') # 폴더
atime_file = os.path.getatime('d:/pylife/os/getc(m)time.xlsx') # 파일
print('atime_folder :', atime_folder)
print('atime_file :', atime_file)
위의 코드를 바탕으로 접근한 날짜를 확인하면 아래와 같습니다.
atime_folder : 1656027887.8841386
atime_file : 1656027883.952642
Convert Time Format 시간 표기법 변경
위에서 숫자를 우리가 흔히 보는 문자열 형태(Fri Jun 24 08:44:43 2022)의 시간 표기법으로 변경하기 위해서는
time 모듈(내장)을 호출해야 합니다.
import os
import time
ctime_file = os.path.getctime('d:/pylife/os/getc(m)time.xlsx')
mtime_file = os.path.getmtime('d:/pylife/os/getc(m)time.xlsx')
atime_file = os.path.getatime('d:/pylife/os')
print(time.ctime(ctime_file))
print(time.ctime(mtime_file))
print(time.ctime(atime_file))
위의 코드를 바탕으로 접근한 날짜를 확인하면 아래와 같습니다.
Fri Jun 24 08:44:43 2022
Fri Jun 24 08:44:43 2022
Fri Jun 24 08:44:47 2022
datetime 모듈의 함수를 이용하여 우리가 익숙한 2022-06-24 08:44:43 형태로도 변환할 수 있습니다.
from datetime import datetime
print(datetime.fromtimestamp(ctime_file).strftime('%Y-%m-%d %H:%M:%S'))
time 모듈을 활용하여 날짜와 시간을 출력하는 다양한 방법에 대해 조금 더 자세히 아시고 싶으시면 아래 링크 참고 바랍니다. (준비 중)
마무리
파일의 생성 시간 및 수정 시간 확인하는 방법을 간단히 알아보았습니다. 이 부분을 활용하면 업무 자동화 프로그램 작성 시 최근 파일 또는 원하는 파일을 선택해서 불러오는 등 다양하게 활용하실 수 있습니다.
'PYTHON > Tips' 카테고리의 다른 글
(Python/Exception) Try ~ Except 예외처리 (0) | 2022.06.28 |
---|---|
(Python/Basic) Print 활용 TIP(feat. datetime) (0) | 2022.06.25 |
(Python/Pandas) Format a number (천 단위 구분 기호 및 기타 서식 적용) (0) | 2022.06.13 |
(5min. Python) Pandas read_excel sheet 불러오기 옵션 (0) | 2022.06.13 |
(Tkinter/Entry) 엔트리 바인드 이벤트(bind event) 설정 (0) | 2022.06.10 |