銀河鉄道

【Python】文字列から拡張子を取得して、文字列で返す|pathlib.Path.suffix

サムネイル
[Python]pathlibfor extension

一番おすすめ|pathlib.Path.suffix

# Return ".ext" or "" (last extension).
# 最後の拡張子を「.ext」または空文字で返す。
from pathlib import Path

def ext(path: str) -> str:
	return Path(path).suffix

# Return "ext" (no leading dot) or "".
# 先頭ドットなしで返す版。
def ext_nodot(path: str) -> str:
	s = Path(path).suffix
	return s[1:] if s.startswith(".") else ""

# Return full composite extension like ".tar.gz".
# 複合拡張子をまとめて返す(例 ".tar.gz")。
def full_ext(path: str) -> str:
	return "".join(Path(path).suffixes)

補足関数

from pathlib import Path

def has_ext(path: str) -> bool:
	# True if the path has any extension (not counting trailing dots or dotfiles).
	# 末尾ドットやドットファイルを除き、拡張子があるか。
	return Path(path).suffix != ""

def change_ext(path: str, new_ext_with_dot: str) -> str:
	# Replace extension using Path API (expects ".txt" form).
	# ".txt"形式を期待して、拡張子を差し替え。
	return str(Path(path).with_suffix(new_ext_with_dot))

def is_hidden_dotfile(path: str) -> bool:
	# True for ".gitignore" style names on POSIX.
	# ".gitignore"のような隠しファイル判定(POSIX文化)。
	name = Path(path).name
	return name.startswith(".") and Path(path).suffix == ""

基本API|Core APIs

  • pathlib.Path.suffix|拡張子(先頭ドット付き)
    例:Path("a.xlsx").suffix".xlsx"Path("noext").suffix""Path("file.").suffix""
  • pathlib.Path.suffixes|拡張子のリスト
    例:Path("a.tar.gz").suffixes[".tar", ".gz"]
  • os.path.splitext|古典的分割
    例:root, ext = os.path.splitext("a.xlsx")ext == ".xlsx"

代表的な境界ケース|Edge cases

"report.xlsx" == ".xlsx"
"a.tar.gz" == ".gz"           # last only
"a.tar.gz" == ".tar.gz"       # full chain
"noext" == ""                 # no extension
"file." == ""                 # trailing dot
".gitignore" == ""            # leading dot = hidden file

Referenced Insights & Citations

| Pathlib|Pathlib |
| Suffix|拡張子(末尾) |
| Suffixes|複合拡張子一覧 |
| Context Manager|コンテキストマネージャ |
| os.path.splitext|splitext関数 |
| Edge Case|境界ケース |
| Hidden File|隠しファイル |
| Trailing Dot|末尾ドット |

Use pathlib for clarity and safety

著者

author
月うさぎ

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

記事一覧