현재 파일의 절대 경로에서 디렉토리만 추출해 내는법

조회수 16556회

발생하는 문제 및 실행환경

디렉토리의 절대 경로만 알아내고 싶은데 os.path.abspath(__file__)C:\\python27\\test.py 같이 파일까지 포함돼서 나와버립니다.

C:\\python27\' 처럼 디렉토리 경로만 알아내려면 어떻게 해야 되나요?

2 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    스크립트가 위치한 디렉토리를 알아낼 때는

    1. 현재 프로그램의 파일 위치를 알아냄 - __file__
    2. 1의 절대 경로를 알아냄 - os.path.abspath(1)사용
    3. 2에서 구한 파일에 디렉토리 이름을 알아냄 - os.path.dirname(2)

    os.path.dirname(os.path.abspath(__file__))로 디렉토리 이름를 추출해 낼 수 있고,

    현재 작업 중인 디렉토리를 알아내려면 os.getcwd() 을 써야 합니다.

    import os
    
    print("dirname:\t" + os.path.dirname(os.path.abspath(__file__)))
    print("getcwd:\t\t" + os.getcwd())
    

    출력 :

    dirname:    /Users/username/PycharmProjects/tempdir
    getcwd:     /Users/username/PycharmProjects/tempdir
    
  • import sys, os

    print(sys.path) # 시스템 path

    print (os.getcwd()) #현재 디렉토리의

    print (os.path.realpath(_ file _))#파일

    print (os.path.dirname(os.path.realpath(_ file _)) )#파일이 위치한 디렉토리

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)