본문 바로가기

Python

os.path 사용하기

os.path 사용하기

파일 읽기/쓰기는 각각 read/write 함수를 사용하면 된다.

그렇다면 경로(path)를 여러가지 방법으로 갖고 놀려면 어떻게 할까?
파이썬은 os.path 모듈로 각종 경로 관련 함수들을 제공한다. 잘 이용해 보자

현재 파이썬 파일 위치 알아내기

os.path.abspath(__file__)
os.path.abspath(__file__)를 사용하자. __file__은 파이썬 예약어로, 현재 .py파일의 위치를 반환한다. 

디렉토리명 알아내기

os.path.dirname(os.path.abspath(__file__))
os.path.dirname(경로문자열)을 사용하자.

파일명 알아내기

os.path.basename('/path/to/abc.txt')

주어진 경로를 절대경로로 정리하기

os.path.abspath('/from/my/path/../../abc.txt')
이런 식으로 상대경로(. 또는 ..) 정리를 해준다. 또한 운영체제에 맞지 않는 경로 구분자가 사용된 경우1도 바로잡아준다.

경로 확장하기

os.path.join('parent', 'child.txt')
os.path.join('parent', *['subdir', 'child.txt'])

을 사용하자. 리스트를 사용해 많은 서브 디렉토리를 표현할 수 있다.

'Python' 카테고리의 다른 글

python multiprocessing  (0) 2016.02.09
python multiprocessing AttributeError  (0) 2016.02.08
메일 발송  (0) 2015.12.08
Random  (0) 2015.12.08
IP확인  (0) 2015.12.08