본문으로 건너뛰기

파이썬에서 파일의 마지막 수정 시간을 얻는 방법.

다음은 파이썬에서 파일의 마지막 수정 시간을 얻는 단계별 튜토리얼입니다:

  1. 필요한 모듈 가져오기:
import os
import time

os 모듈은 운영 체제와 상호 작용하기 위해, time 모듈은 시간 관련 기능을 사용하기 위해 가져와야 합니다.

  1. 파일 경로 가져오기:
file_path = '파일/경로/여기에/입력.txt'

'파일/경로/여기에/입력.txt'를 확인하려는 파일의 실제 경로로 대체하세요.

  1. 파일이 존재하는지 확인하기:
if os.path.exists(file_path):

os.path.exists() 함수를 사용하여 주어진 경로에 파일이 있는지 확인합니다.

  1. 파일의 마지막 수정 시간 가져오기:
    modified_time = os.path.getmtime(file_path)

os.path.getmtime() 함수는 파일의 마지막 수정 시간을 타임스탬프로 반환합니다.

  1. 타임스탬프를 읽기 가능한 형식으로 변환하기:
    modified_time_readable = time.ctime(modified_time)

time.ctime() 함수를 사용하여 타임스탬프를 읽기 가능한 형식으로 변환합니다. 이렇게 하면 수정된 시간의 문자열 표현이 얻어집니다.

  1. 마지막 수정 시간 출력하기:
    print("마지막 수정 시간:", modified_time_readable)

이렇게 하면 파일의 마지막 수정 시간이 사람이 읽을 수 있는 형식으로 출력됩니다.

모두를 함께 넣으면 다음과 같이 완성된 코드가 됩니다:

import os
import time

file_path = '파일/경로/여기에/입력.txt'

if os.path.exists(file_path):
modified_time = os.path.getmtime(file_path)
modified_time_readable = time.ctime(modified_time)
print("마지막 수정 시간:", modified_time_readable)
else:
print("파일을 찾을 수 없습니다!")

반드시 '파일/경로/여기에/입력.txt'를 실제 파일의 경로로 대체하세요.