1
6

【Python】ディレクトリ・パス取得関連(os, pathlib, glob)

Last updated at Posted at 2021-11-06

概要

Pythonのパスやディレクトリを取得する方法よく忘れてしまうので、
備忘録として残しておきます。
今回はospathlibglobモジュールあたりの話です。

osモジュール

__ file __はPythonファイル(今回でいうpath.py)の絶対パスです。

絶対パスを取得(os.path.abspath())

path.py
path = os.path.abspath(__file__)
print("Absolute Path: {}".format(path))
# Absolute Path: /Users/.../path.py

相対パスを取得(os.path.relpath())

第2引数は対象としたい相対基準のパス。

path.py
relPath = os.path.relpath(__file__, "./")
print("Relative Path: {}".format(relPath))
# Relative Path: path.py

現在地のディレクトリを取得()

path.py
dire = os.getcwd()
print("Directry: {}".format(dire))
# Directry: /Users/...

ディレクトリ名とファイル名を分割(os.path.split())

path.py
path = os.path.split(__file__)
print("Directry: {}, FileName: {}".format(path[0], path[1]))
# Directry: /Users/..., FileName: path.py

ディレクトリ名取得(os.path.dirname())

path.py
dire = os.path.dirname(__file__)
print("Directry: {}".format(dire))
# Directry: /Users/...

ファイル名取得(os.path.basename())

path.py
fname = os.path.basename(__file__)
print("FileName: {}".format(fname))
# FileName: path.py

pathlibモジュール

相対パス→絶対パス

path.py
absPath = pathlib.Path("./path.py").resolve()
print("Absolute Path: {}".format(absPath))
# Absolute Path: /Users/.../path.py

相対パス→絶対パス

path.py
relPath = pathlib.Path(__file__).relative_to(os.getcwd())
print("Relative Path: {}".format(relPath))
# Relative Path: path.py

globモジュール

変数filesはリスト型です。
filesの並びがテキトーなので、整形したものが欲しい場合はsortedを使用。

該当するファイルリストを取り出し

path.py
files = glob("test/*.py")
for f in files:
    print("File: {}".format(f))
# File: test/test4.py
# File: test/test1.py
# File: test/test7.py
path.py
files = sorted(glob("test/*.py"))
for f in files:
    print("File: {}".format(f))
# File: test/test1.py
# File: test/test4.py
# File: test/test7.py

その他

全てまとめたソースコードをGitHubに置いています。

1
6
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
1
6