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軸の目盛りを反対方向につけたい場合。

デフォルトでは、x軸はグラフの下に、y軸は左側につけられる。 例 import numpy as np from matplotlib import pyplot as plt x = np.lins …

no image

python3 で、フォルダがなければ作成するプログラム

os.mkdir() 関数を使う。 すでにフォルダが存在している場合は、エラーを表示する。 例 import os folder_name = ‘./python_create_folder’ try …

no image

matplotlib で、複数のグラフを簡単にプロットする方法

変数を並べて書くと、次のように自動的に順番を理解してグラフを表示してくれる。 例 import numpy as np from matplotlib import pyplot as plt fro …

no image

pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

リストを iter に変えたあと、… next() を使う。 参考リンク https://www.programiz.com/python-programming/methods/buil …

no image

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

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