銀河鉄道

【Python】フォルダとファイルの存在確認|pathlib

サムネイル
[Python]pathlib存在確認

フォルダの存在確認

from pathlib import Path

def folder_exists(folder_path: str) -> bool:
    return Path(folder_path).is_dir()

ファイルの存在確認

from pathlib import Path

def file_exists(full_path: str) -> bool:
    return Path(full_path).exists()

pathlib

  • Path.is_dir()
    • 指定パスがフォルダなら True
    • ファイルの場合は False
  • Path.exists()
    • Return True if the path points to an existing file or directory.

出典

In Python, always prefer pathlib for file operations—it’s cleaner and more modern.
Pythonでは、pathlib を使うのがきれい.

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧