■ はじめに
https://dk521123.hatenablog.com/entry/2019/09/02/000000
の続き。 「パスからファイル名を抜き出す」とか 「ファイル名から拡張子を抜き出す」とかを結構やることが多く なんだっけ?っていつもなるので、まとめておく
目次
【1】パス、ファイル名、拡張子を抽出 【2】ファイル名 or フォルダ名 のみ抽出 【3】パスのみ抽出 【4】直近の親フォルダ名を取得する 【5】パス内のファイル一覧を取得する
【1】パス、ファイル名、拡張子を抽出
import os file_name = 'input.csv' # ('', 'input.csv') print(os.path.split(file_name)) # ('input', '.csv') print(os.path.splitext(file_name)) path = 'C:/tmp/input.csv' # ('C:/tmp', 'input.csv') print(os.path.split(path)) # ('C:/tmp/input', '.csv') print(os.path.splitext(path)) s3_path = 's3://your-bucket/xxx/sample.txt' # ('s3://your-bucket/xxx', 'sample.txt') print(os.path.split(s3_path)) # ('s3://your-bucket/xxx/sample', '.txt') print(os.path.splitext(s3_path)) path, file_extention = os.path.splitext(s3_path) # True print(file_extention in ['.txt', '.csv']) # False print(file_extention in ['.sql', '.hql']) # False print(file_extention not in ['.txt', '.csv']) # True print(file_extention not in ['.sql', '.hql'])
【2】ファイル名 or フォルダ名 のみ抽出
# input.csv print(os.path.basename(path))
【3】パスのみ抽出
# C:/tmp print(os.path.dirname(path))
【4】直近の親フォルダ名を取得する
# tmp print(os.path.basename(os.path.dirname(path)))
https://note.nkmk.me/python-os-basename-dirname-split-splitext/
サンプル
import os # ファイル名(拡張子なし) def get_filename_without_ext(target_path): file_name = os.path.basename(target_path) return os.path.splitext(file_name)[0] # 親フォルダ名 def get_parent_dir_name(target_path): return os.path.basename(os.path.dirname(target_path)) # ('/abc/def', 'hello.txt') print(os.path.split('/abc/def/hello.txt')) # ('/abc/def/hello', '.txt') print(os.path.splitext('/abc/def/hello.txt')) # hello.txt print(os.path.basename('/abc/def/hello.txt')) # hello print(get_filename_without_ext('/abc/def/hello.txt')) # /abc/def print(os.path.dirname('/abc/def/hello.txt')) # def print(get_parent_dir_name('/abc/def/hello.txt'))
【5】パス内のファイル一覧を取得する
* 「os.listdir(path)」を使う
https://note.nkmk.me/python-listdir-isfile-isdir/
特定パターンのファイル一覧が欲しい場合
* 「glob.glob("【パス】/*【拡張子】")」を使う => e.g. glob.glob("/xxxx/xxxx/*txt")
サンプル
例1:os.listdir
path = "./test" files = os.listdir(path) print(type(files)) # <class 'list'> print(files) # ['input1.dot', 'input2.dot', 'input3.dot', 'input4.dot']
例2:glob.glob
import glob for paht in glob.glob("/xxxx/xxxx/*txt") # txtのものしかとってこない print(path)
関連記事
Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / フォルダ・ファイル操作 ~
https://dk521123.hatenablog.com/entry/2019/09/02/000000
Python ~ 基本編 / ファイル読込・書込 ~
https://dk521123.hatenablog.com/entry/2019/10/07/000000
Python ~ 基本編 / クラス・継承 ~
https://dk521123.hatenablog.com/entry/2019/08/29/220537
DOT言語表示ツール ~ d3-graphviz ~
https://dk521123.hatenablog.com/entry/2023/06/18/102448