Pythonでのパス操作まとめ
2020-03-19
2020-03-19
前置き
Pythonではファイルとフォルダ関連のタスクを実行する時、便利なos.pathとpathlibモジュールを使用します。Pathlibモジュールは、Python 3.4以降のバージョンから入手できます。
os.pathを使ってパス操作
ファイルまたはディレクトリが存在するか確認
```>>> import os
>>> os.path.exists("./test_files/file1.txt")
True
>>> os.path.exists("./test_files")
True
```>>> os.path.exists("./test_files/file1.txt")
True
>>> os.path.exists("./test_files")
True
ファイルであることを確認
```>>> os.path.isfile('./test_files/file1.txt')
True
```True
ディレクトリであることを確認
```>>> os.path.isdir('./test_files')
True
```True
パスからファイル名/ディレクトリを取得
```>>> test_path = "./test_files/file1.txt"
>>> os.path.basename(test_path)
'file1.txt'
>>> os.path.dirname(test_path)
'./test_files'
```>>> os.path.basename(test_path)
'file1.txt'
>>> os.path.dirname(test_path)
'./test_files'
ディレクトリとファイルを結合
```>>> test_path = "./test_files"
>>> test_file = "file1.txt"
>>> os.path.join(test_path, test_file)
'./test_files/file1.txt'
```>>> test_file = "file1.txt"
>>> os.path.join(test_path, test_file)
'./test_files/file1.txt'
ディレクトリとファイルを分割
```>>> test_path = "./test_files/file1.txt"
>>> os.path.split(test_path)
('./test_files', 'file1.txt')
```>>> os.path.split(test_path)
('./test_files', 'file1.txt')
pathlibを使ってパス操作
ディレクトリとファイルを結合
```>>> from pathlib import Path
>>> test_path = Path("./test_files")
>>> test_file = "file1.txt"
>>> test_path / test_file
PosixPath('test_files/file1.txt')
```>>> test_path = Path("./test_files")
>>> test_file = "file1.txt"
>>> test_path / test_file
PosixPath('test_files/file1.txt')
ファイルまたはディレクトリが存在するか確認
```>>> test = Path("./test_files/file1.txt")
>>> test.exists()
True
```>>> test.exists()
True
パスからファイル名を取得
```>>> test = Path("./test_files/file1.txt")
>>> test.name
'file1.txt'
>>> test.stem
'file1'
>>> test.suffix
'.txt'
```>>> test.name
'file1.txt'
>>> test.stem
'file1'
>>> test.suffix
'.txt'
絶対パスを取得
```>>> test = Path("./test_files/file1.txt")
>>> test.absolute()
PosixPath('/Users/aaa/Desktop/test_files/file1.txt')
```>>> test.absolute()
PosixPath('/Users/aaa/Desktop/test_files/file1.txt')
ファイルであることを確認
```>>> test = Path("./test_files/file1.txt")
>>> test.is_file()
True
```>>> test.is_file()
True
ディレクトリであることを確認
```>>> test = Path("./test_files")
>>> test.is_dir()
True
``` >>> test.is_dir()
True