python3

python3 で、pathlib を使ってファイルの拡張子を取得する方法

投稿日:2021年4月10日 更新日:

pathlib モジュールの stem を使う。

この書き方は、python 3.4 以降で使えるようになった。

https://docs.python.org/3/library/pathlib.html

from pathlib import Path

jpgfile = Path('Users/myuser/Desktop/some_jpg_file.jpg').stem
print('ファイル名1: ' + jpgfile)

targz_file = Path(Path('/Users/myuser/Desktop/some_targz_file.tar.gz').stem).stem
print('ファイル名2: ' + targz_file)

結果

ファイル名1: some_jpg_file
ファイル名2: some_targz_file

-python3
-,

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で、x,y の軸上の数値を表示する方法

ax の xtics と ytics を使って表示する。 詳細は次のドキュメントを参照。 https://matplotlib.org/stable/gallery/lines_bars_and_ma …

no image

matplotlib で、凡例を表示する方法

データに label を関連付け、plt.legend() で凡例を表示する。 例 from matplotlib import pyplot as plt data_x = [25,26,2 …

no image

python3 で辞書(dictionary)を削除する

clear() することによって、辞書が存在した状態のまま、キーと値をすべて削除することができる。 例 dict1 = {“名前”:”太郎”, “年齢”: 20, “住所”: “東京都千代田区大手町1 …

no image

matplotlib で、ヒストグラムを作成する方法

ヒストグラムを描くには、data_hist を使う。 ヒストグラムの縦棒の数は bins で指定する。 例 from matplotlib import pyplot as plt data_hist …

no image

python3 で辞書からタプルを作成する

辞書に対して、items() メソッドを使うと、タプルを作成することができる。 例 cities = {‘東京’:1000,’大阪’:700, ‘広島’:100} for a,b in cities. …