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

python3 で区切り文字を省略して文字列を分割する

string の split 関数は、区切り文字を指定しない場合には半角スペースや改行・タブ文字を使って自動的に分割してくれる。分割結果はリストで返される。 例 str1 = ‘Hello, nice …

no image

matplotlib でグラフ表示ウィンドウの画面上の位置を自由に設定する方法

matplotlib.use(‘TkAgg’) としておき、 get_current_fig_manager().window.wm_geometry(“+20+50”) として、(+20+50)のと …

no image

python3 でタプルを指定した要素で順に並び替える

タプルを、指定した要素で並び替えることができる。「key=lambda x 」で、引数 x を指定。lambda は無名関数を表す。 例 record = [(‘織田信長’, 1534, 15 …

no image

python3 で csv ファイルを読み込んで、最初の数行を表示する方法

以下の例では、空の配列 data を用意しておき、最初の3行を読み込んでおく。 例 import csv with open(‘data.csv’,’r’) as csv_file: csv_read …

no image

matplotlib でグラフの背景の色を変える方法(facecolor)

次のように、axes で facecolor を変更すればよい。 例 from matplotlib import pyplot as plt x = [2,7,8] y = [7,1 …