Python × 業務効率化 メモ

Python初心者による業務効率化・RPA関連の学習メモ / 資格勉強の記録

【Python3】os.path のよく使うファイルパス操作 まとめ

Python 標準ライブラリ(Python 側に既に埋め込まれていてインストール不要のライブラリ)の os モジュール。
ファイルの自動処理を Python で行う際に必ず使うので、使い方をメモしておく。
今回は os.path モジュールによるファイルパス操作全般について。


インストール不要だが、モジュールのインポートは必要なので最初にしておく。

import os

ファイルパスを作成(結合)・分離:join / split

# フォルダパス
dirpath = r"C:\test_dir"
# ファイル名
filename = r"test_file.txt"

# join:結合してファイルパスを作成
filepath = os.path.join(dirpath, filename)
print(filepath) # 出力:C:\test_dir\test_file.txt

# split:ファイルパス(filepath)を、パス構成要素の末尾とそれ以前に分離
path = os.path.split(filepath)
print(path) # 出力:('C:\\test_dir', 'test_file.txt')


os.path.split は結果を (head, tail) のタプルで返す。
ファイルパスの構成要素の末尾がフォルダなら、tail はフォルダ名になる。

# path[0]:"C:\\test_dir"
print(os.path.split(path[0])) # 出力:('C:\\', 'test_dir')

ファイルパスからフォルダ名やファイル名、拡張子を取得:dirname / basename / splitext

# ファイルパス
filepath = r"C:\test_dir\test_file.txt"

# dirname:親フォルダのパスを取得
# os.path.split の結果のペアの1番目
dirpath = os.path.dirname(filepath)
print(dirpath) # 出力:C:\test_dir

# basename:ファイル名(拡張子あり)を取得
# os.path.split の結果のペアの2番目
basename = os.path.basename(filepath)
print(basename) # 出力:test_file.txt

# splitext:ファイルパスを拡張子(extension)とそれ以前に分離
ext = os.path.splitext(filepath)[1] # ペアの2番目が拡張子
print(ext) # 出力:.txt

# splitext, basename:ファイル名(拡張子なし)を取得
# basename = os.path.basename(filepath)
basename_without_ext = os.path.splitext(basename)[0]
print(basename_without_ext) # 出力:test_file

# basename, dirname:親フォルダ名のみを取得
# dirpath = os.path.dirname(filepath)
parent_dirname = os.path.basename(dirpath)
print(parent_dirname) # 出力:test_dir

指定のファイル・フォルダの存在確認:isfile / isdir / exists

# フォルダパス
dirpath = r"C:\test_dir"
# ファイルパス
filepath = r"C:\test_dir\test_file.txt"

# isfile:ファイルの存在確認
# 存在すれば True / フォルダパスの場合は問答無用で False
print(os.path.isfile(filepath)) # 出力:True or False
print(os.path.isfile(dirpath)) # 出力:False

# isdir:フォルダの存在確認
# 存在すれば True / ファイルパスの場合は問答無用で False
print(os.path.isdir(dirpath)) # 出力:True or False
print(os.path.isdir(filepath)) # 出力:False

# exists:有効なパスか確認
# ファイル・フォルダが存在すれば True
print(os.path.exists(filepath)) # 出力:True or False
print(os.path.exists(dirpath)) # 出力:True or False


後日追記。