この記事では、Pythonでパスを結合・分割して整形する方法を解説します。
パスを結合するには、os.pathモジュールのjoin()関数を使います。環境に合ったセパレータを使ってくれるのでstr.join()を使うよりも安全です。
import os os.path.join(path, *paths)
適当にディレクトリ名やファイル名を結合してパスを生成してみます。
import os dirname = 'dir' filename = 'test.py' # ディレクトリ名とファイル名を結合し、パスを生成 path = os.path.join(dirname, filename) print(path) # dir/test.py # いくつでも結合できる subdirname = 'subdir' path = os.path.join(dirname, subdirname, filename) print(path) # dir/subdir/test.py # もちろんパスも指定できる current = os.getcwd() path = os.path.join(current, dirname, subdirname, filename) print(path) # /Users/user/Desktop/Python/dir/subdir/test.py
無事にパスを結合することができました。
パスを分割するには、os.pathモジュールのsplit()関数、またはsplitext()関数を使います。split()関数はパスの末尾を分割し、splitext()関数は拡張子を分割します。
import os os.path.split(path) os.path.splitext(path)
適当なパスを分割してみます。
import os path = '/Users/user/Desktop/Python/dir/subdir/test.py' split_path = os.path.split(path) print(split_path) # ('/Users/user/Desktop/Python/dir/subdir', 'test.py') split_path = os.path.splitext(path) print(split_path) # ('/Users/user/Desktop/Python/dir/subdir/test', '.py') path = '/Users/user/Desktop/Python/dir/subdir' split_path = os.path.split(path) print(split_path) # ('/Users/user/Desktop/Python/dir', 'subdir') split_path = os.path.splitext(path) print(split_path) # ('/Users/user/Desktop/Python/dir/subdir', '')
パスを分割することができました。