파이썬에서 현재 스크립트 파일 디렉토리를 얻는 방법

Jinku Hu 2023년1월30일
  1. 파이썬은 작업 디렉토리를 얻는다
  2. 파이썬은 스크립트 파일 디렉토리를 얻는다
파이썬에서 현재 스크립트 파일 디렉토리를 얻는 방법

Python 3 기본 자습서에서 파일 및 디렉터리 작업을 소개했습니다. 이 섹션에서는 실행 스크립트의 상대 및 절대 경로를 얻는 방법을 보여줍니다.

파이썬은 작업 디렉토리를 얻는다

os.getcwd()함수는 현재 작업 디렉토리를 반환합니다.

Python 유휴 프롬프트에서 실행하면 결과는 Python IDLE 의 경로입니다.

파이썬은 스크립트 파일 디렉토리를 얻는다

스크립트 파일 경로는 특수 전역 변수__file__과 함께 global namespace에서 찾을 수 있습니다. 작업 디렉토리에 상대적인 스크립트 파일의 상대 경로를 리턴합니다.

아래 예제 코드에서 방금 소개 한 기능을 사용하는 방법을 보여줍니다.

import os

wd = os.getcwd()
print("working directory is ", wd)

filePath = __file__
print("This script file path is ", filePath)

absFilePath = os.path.abspath(__file__)
print("This script absolute path is ", absFilePath)

path, filename = os.path.split(absFilePath)
print("Script file path is {}, filename is {}".format(path, filename))
absFilePath = os.path.abspath(__file__)

os.path.abspath(__file__)는 주어진 상대 경로의 절대 경로를 반환합니다.

path, filename = os.path.split(absFilePath)

os.path.split()함수는 파일 경로를 순수한 경로와 순수한 파일 이름으로 분할합니다.

작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook