LoginSignup
6
4

【Python】一つ上の階層のファイルのパスを取得する

Posted at

はじめに

Pythonを書く機会があり、実装に迷ったポイントがあったので記録しておきます。

ディレクトリ構成

root
  ├ src
  │  └ example.py
  └ example.txt

実装

example.py
import os

# 現在のスクリプトファイルのディレクトリを取得
current_dir = os.path.dirname(os.path.abspath(__file__))

# 1つ上の階層のディレクトリパスを取得
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))

# 1つ上の階層にあるファイルのパスを作成
file_path = os.path.join(parent_dir, "example.txt")

おわり

Pythonにはたくさんライブラリがあって便利ですね

6
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4