LoginSignup
0
0

More than 1 year has passed since last update.

pathlibメモ

Last updated at Posted at 2021-11-20

基本操作

from pathlib import Path
imgs=Path("imgs")
imgs/"test.png"
# PosixPath('imgs/test,png)

ディレクトリ生成

dirc=Path("dirc")
dirc.mkdir(exist_ok=True) 

ファイルの中身一覧

dirc=Path("dirc")
files=list(dirc.iterdir())

文字にする

基本的に(すべての親ディレクトリ)/ファイル名という扱い

img=Path("dirc/test.png")

# 文字列に
str(img)
# 'dirc/test.png'

# ファイル名
img.name
# 'test.png'

# ファイル名のみ
img.stem
# 'test'

# 拡張子
img.suffix
# '.png'

#親ディレクトリの取得
img.parent
# PosixPath('dirc')

img=Path("dirc/test1/test2/test.png")
# PosixPath('dirc/test1/test2')

ファイルの存在確認

dirc=Path("dirc")

# 存在するかどうか
dirc..exists()

# ディレクトリかどうか(存在しなくてもFalse)
dirc.is_dir()

# ファイルかどうか(存在しなくてもFalse)
dirc.is_file()

使用例

./testA/内の画像を全て読み込んで./testB/内のすべてのディレクトリ内に保存

test.py
from pathlib import Path
import cv2
testA=Path("testA")
testB=Path("testB")
testA_files=list(testA.iterdir())
imgs=[]
names=[]
for testA_file in testA_files:
     if ".png" == testA_file.suffix:
             names.append(testA_file.name)
             imgs.append(cv2.imread(str(testA_file)))

for testB_dir in testB_dirs:
     if testB_dir.is_dir():
             for img,name in zip(imgs,names):
                     cv2.imwrite(str(testB_dir/name),img)

0
0
1

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
0
0