Pythonでファイルの拡張子を取得する方法

Pythonのosモジュールのsplitext()関数を使用することで、ファイルの拡張子を取得できます。この関数は、ファイルパスをルートと拡張子の2つの値を持つタプルに分割します。

Pythonでファイル拡張子を取得

Pythonでファイルの拡張子を取得する、簡単なプログラムをこちらに用意しました。

import os

# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/scdev/abc.txt")

print(file_name)
print(file_extension)

print(os.path.splitext("/Users/scdev/.bashrc"))
print(os.path.splitext("/Users/scdev/a.b/image.png"))

出力: 目標は、日本語で以下の文を言い換えることです。

File Extension Python
  • In the first example, we are directly unpacking the tuple values to the two variables.
  • Note that the .bashrc file has no extension. The dot is added to the file name to make it a hidden file.
  • In the third example, there is a dot in the directory name.

Pathlibモジュールを使用して、ファイルの拡張子を取得する。

私たちはpathlibモジュールを使用して、ファイルの拡張子を取得することもできます。このモジュールはPython 3.4リリースで紹介されました。

>>> import pathlib
>>> pathlib.Path("/Users/scdev/abc.txt").suffix
'.txt'
>>> pathlib.Path("/Users/scdev/.bashrc").suffix
''
>>> pathlib.Path("/Users/scdev/.bashrc")
PosixPath('/Users/scdev/.bashrc')
>>> pathlib.Path("/Users/scdev/a.b/abc.jpg").suffix
'.jpg'
>>> 

結論

標準的な方法を使用してファイルの拡張子を取得する方が常に良いです。すでにosモジュールを使用している場合は、splitext()メソッドを使用してください。オブジェクト指向アプローチの場合は、pathlibモジュールを使用してください。

コメントを残す 0

Your email address will not be published. Required fields are marked *