0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Pythonメモ】実行中のファイル・そのファイルの入ってるディレクトリ・カレントディレクトリ・相対パスで指定したファイル の絶対パスの取得

Last updated at Posted at 2021-04-14

しょっちゅう忘れてしまうのでまとめておきます。
Windows10
Python3.8.5
virtualenv

以下のフォルダ構成になっています。
C:\Users\user\Desktop\TEST\asai\hukai\get_abspath.py
TESTをカレントディレクトリとし、ここから2つ下の階層に置いてあるget_abspath.pyを実行します。

実行中のファイルとディレクトリの取得

get_abspath.py

import os

# 実行しているpythonファイルの絶対パス
current_pyfile = os.path.abspath(__file__)
# 実行しているpythonファイルが入ってるディレクトリの絶対パス
current_pyfiles_dir = os.path.dirname(current_pyfile)
# カレントディレクトリの絶対パス
current_dir = os.getcwd()

print(current_pyfile)
print(current_pyfiles_dir)
print(current_dir)

実行結果

(venv) C:\Users\user\Desktop\TEST>python asai\hukai\get_abspath.py
C:\Users\user\Desktop\TEST\asai\hukai\get_abspath.py
C:\Users\user\Desktop\TEST\asai\hukai
C:\Users\user\Desktop\TEST

ファイルのパス生成と存在チェック

os.path.abspath()というコマンドを使うと、与えたファイル名で絶対パスを生成してくれます。ここでは存在しないファイルでも扱えます。
さきほどと同じ場所にget_usopath.pyを書いて実行してみます。
C:\Users\user\Desktop\TEST\asai\hukai\get_usopath.py

get_usopath.py
import os

# 存在しないファイルを指定して絶対パスを生成
poem_path = os.path.abspath("./uso_dir/poem.txt")
# そのファイルが入ってるディレクトリの絶対パス
poems_dir_path = os.path.dirname(poem_path)

print(poem_path)
print(poems_dir_path)

# 上の2つのパスの存在チェック
print(os.path.isfile(poem_path))
print(os.path.isdir(poems_dir_path))
(venv) C:\Users\user\Desktop\TEST>python asai\hukai\get_usopath.py
C:\Users\user\Desktop\TEST\uso_dir\poem.txt
C:\Users\user\Desktop\TEST\uso_dir
False
False

参考

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?