본문 바로가기
  • Hello_
Python/OS

[Python] os - os.path 활용

by LDwDL 2022. 9. 9.
728x90
반응형

오늘은 많이 사용되는 os.path.join()에 대해 소개하고자 하였지만 os.path 내에 어떠한 함수가 있는지 궁금하여 찾아보던 중 소개해줄 함수들이 있어 몇몇 함수들을 추려서 같이 포스팅을 하겠다.

 

os.path.join()

os.path.join()은 상위 경로와 하위 경로의 문자열들을 하나의 경로 형태의 문자열로 합쳐주는데 주로 사용이 된다.

 

[문제 발생 코드]

import os

parent_path = './parent_path'
sub_path = 'sub_path'
folder = 'folder'

combined_path = parent_path + sub_path + folder
print(combined_path)
# ./parent_pathsub_pathfolder

물론 sub_path와 folder에 '/'를 포함하여 경로 형태로 직접 구성해주어도 되지만, 비효율적인 방법이다.

 

[os.path.join() 활용]

new_combined_path = os.path.join(parent_path, sub_path, folder)
print(new_combined_path)
# ./parent_path/sub_path/folder

위 결과와 같이 경로명과 파일명만 입력으로 넣어주면 보기 좋게 경로 형태로 구성시켜준다.

 

os.path.isfile(), os.path.isdir()

os.path.isfile("파일")는 해당 파일이 존재하면 True, 아니라면 False를 리턴한다.

마찬가지로 os.path.isdir("경로")도 입력된 경로가 존재하면 True, 반대의 경우라면 False를 반환한다.

 

os.path.isabs()

os.path.isabs("경로")는 입력된 경로가 절대 경로라면 True, 상대 경로라면 False를 리턴한다.

 

os.path.getatime(), os.path.getmtime(), os.path.getctime()

os.path.getatime("경로") - 경로의 마지막 액세스 시간을 리턴 

os.path.getmtime("경로") - 경로의 마지막 수정 시간을 리턴

os.path.getctime("경로") - 경로의 마지막 생성 시간을 리턴

 

- 필자의 생각으론.. access, modification, creation의 앞글자를 참조하여 구성한 함수인 것 같다.

 

os.path.samefile()

os.path.samefile("경로1","경로2")은 입력되는 두 개의 경로가 같다면 True를 리턴한다.

 

 

 

 

728x90
반응형

댓글