環境設定 数値 文字列 正規表現 リスト タプル 集合 辞書 ループ 関数 クラス データクラス 時間 パス ファイル スクレイピング その他

Python で現在のファイルがあるディレクトリのパスを取得する

最終更新日 2023.02.18

現在のファイルを表すパスオブジェクトは Path(__file__) で、その親は parent です。

from pathlib import Path

parent = Path(__file__).parent

print(parent.as_posix())  # /Users/Alice/test/test/path

as_posix() は絶対パスを返します。

os.getcwd()

import os

folder = os.getcwd()

print(folder)  # /Users/Alice/test/test/path

os ライブラリの getcwd は現在のディレクトリのパスを返します。