Pythonでパス名操作関数を使う

Pythonでファイル操作するときによく使う関数をまとめます。

os.pathの関数

サンプルコードに使うパス名は、実行するプログラムのファイルそのものとします。
__file__を使います。

print(__file__)
# c:\test\test.py

パスが存在するか、ディレクトリか、ファイルか、を返す関数です。

print(os.path.exists(__file__))
# True
# パスが存在するか。

print(os.path.isdir(__file__))
# False
# パスがディレクトリかどうか。

print(os.path.isfile(__file__))
# True
# パスがファイルかどうか。

ディレクトリ名、ファイル名、を返す関数です。

print(os.path.dirname(__file__))
# c:\test
# パスのディレクトリ名を返す。

print(os.path.basename(__file__))
# test.py
# パスの末尾の部分を返す。ファイルなら拡張子も含まれる。

print(os.path.basename(os.path.dirname(__file__)))
# test
# パスが存在するすぐ上のディレクトリ名が知りたいときは、こうする。

パスからディレクトリ名、ファイル名、拡張子、などの情報を取得する関数です。

print(os.path.split(__file__))
# ('c:\\test', 'test.py')
# パスを(head, tail)に分割する。

print(os.path.splitdrive(__file__))
# ('c:', '\\test\\test.py')
# パスを(drive, tail)に分割する。

print(os.path.splitext(__file__))
# ('c:\\test\\test', '.py')
# パスを(root, ext)に分割する。

print(os.path.splitext(os.path.basename(__file__)))
# ('test', '.py')
# ファイル名から拡張子を分離させる

プログラムでファイル検索していると、パス名の中に”..”が入ることがあります。
それをos.path.normpathで正規化できます。

path = os.path.join(__file__, '..')
print(path)
print(len(os.listdir(path)))
# c:\test\test.py\..
# 5

path2 = os.path.normpath(path)
print(path2)
print(len(os.listdir(path)))
# c:\test
# 5

print(os.path.samefile(path, path2))
# True
# normpathしても、パスは同じ。

os.pathの仕様書です。

os.pathの関数の使いどころ

os.pathの関数を使ってサンプルコードを書いてみます。

ディレクトリ構成は以下のようになっています。

$ c:\test>tree /f .
C:\TEST
│  test.py
│  test_00.txt
│  test_01.csv
│  test_02.xlsx
│
├─dir_10
│      test_10.txt
│
└─dir_20
        test_20.txt

ファイル検索などで、下位のディレクトリの階層構造を探るときは以下のようなコードになります。
CSVファイルを検索するサンプルコードを書いてみました。

cur_path = os.path.dirname(__file__)
print(cur_path)
# c:\test

for p in os.listdir(cur_path):
    path = os.path.join(cur_path, p)

    if os.path.isdir(path):
        print(f'directory: {path}')
    elif os.path.isfile(path):
        print(f'file: {path}')
        root, ext = os.path.splitext(path)
        if 'csv' in ext:
            print(f'  find the target: {path}')
    else:
        pass

# directory: c:\test\dir_10
# directory: c:\test\dir_20
# file: c:\test\test.py
# file: c:\test\test_00.txt
# file: c:\test\test_01.csv
#   find the target: c:\test\test_01.csv
# file: c:\test\test_02.xlsx