【Python】文字列から拡張子を取得して、文字列で返す|pathlib.Path.suffix
作成日:2025-10-05
更新日:2025-10-06

一番おすすめ|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
- Python Software Foundation. (n.d.). pathlib — Object-oriented filesystem paths. https://docs.python.org/3/library/pathlib.html
- Python Software Foundation. (n.d.). os.path — Common pathname manipulations. https://docs.python.org/3/library/os.path.html
- Python Software Foundation. (n.d.). File Objects. https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
| Pathlib|Pathlib |
| Suffix|拡張子(末尾) |
| Suffixes|複合拡張子一覧 |
| Context Manager|コンテキストマネージャ |
| os.path.splitext|splitext関数 |
| Edge Case|境界ケース |
| Hidden File|隠しファイル |
| Trailing Dot|末尾ドット |
Use
pathlib
for clarity and safety
2025-10-05
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[Python]getdictionary 【Python】dictionaryから値を取得する2つの違い -
[Python]Stringsplit 【Python】文字列を抜き出す|.split -
[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com -
[Python]inString 【Python】指定の文字列が含まれているか|in -
[Python]stripspace 【Python】先頭,末尾,両端の空白を削除する|.strip -
[Python]Write a 1D arrayvia pandas 【Python】Excelに書き出す|pandas.ExcelWriter