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 でクラス内からだけアクセスするメソッドを作る方法

1.メソッド内でメソッドを定義する2.メソッド最初にアンダースコアをつける(慣習)例: def _some_internal_func(self): … このうち、2.のメソッド名先頭にアンダース …

no image

python3 でリストを結合する方法

2つのリストを結合して、「リストのリストを作りたい場合」と、「1つの長いリストを作りたい」場合がある。 それぞれ、次のようにする。 例 # リスト2つを用意 l_1 = [1,2,3] l_2 …

no image

matplotlib で、グラフの線の幅を変更する方法

lw で、線幅を数字で指定すればよい。 例 from matplotlib import pyplot as plt data_x = [25,26,27] data_y = [39, …

no image

python3 で、csv ファイルを読み込んで条件をみたす行の内容を表示する方法

csv.reader で読み込み、各行を読み込んで判定する。 例 import csv with open(‘data.csv’, ‘r’) as csv_file: reader = csv.rea …

no image

gnuplot で、グラフの形を正方形にする方法

set size square または、その省略形で set size sq というコマンドを使えば正方形の中にグラフを描くことができる。 例 set size square plot cos(x) …