現在の Python のスクリプトファイルのフォルダパスを取得する方法

Python 3 の基本チュートリアル]で、ファイルとディレクトリの操作について説明します。このセクションでは、実行中のスクリプトの相対パスと絶対パスを得る方法を示します。
Python 作業ディレクトリを取得する
os.getcwd()
関数は、現在の作業ディレクトリを返します。
Python IDLE
でこのコマンドを実行すると、返ってきた結果が Python IDLE
のパスです。
現在実行されているファイルのディレクトリを Python で取得する
スクリプトファイルへのパスはグローバル名前空間にあり、その変数名は __file__
です。この変数は、Python 作業ディレクトリに対する相対パスです。
サンプルコードを使って、先ほど紹介した知識を実際に操作します。
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
関数の結果は、入力パラメータとしての相対パスの絶対パスです。
path, filename = os.path.split(absFilePath)
os.path.split()
関数は 2つの結果を返しました。一つはファイルの純粋なパス名で、もう一つは純粋なファイル名です。
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