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 で、軸に垂直・平行な線を書く方法

axhline, axvline を使ってx,y軸に平行な線を描くことができる。 https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot …

no image

python3 で、csv ファイルの日付・数字を読み取る方法

csv をインポートすると、row in reader はリストになっている。 次のようにして、各行の要素を取り出して表示することができる。 例 import csv with open(‘data. …

no image

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

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

no image

matplotlib で、縦横の線(グリッド)を描く方法

pyplot grid で縦横線(罫線のようなもの)を引くことができる。 例 from matplotlib import pyplot as plt data_x = [25,26,27] …

no image

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

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