0
0

More than 1 year has passed since last update.

python .globの使い方

Last updated at Posted at 2023-01-19

ディレクトリ構成

dirname
┣1.txt
┣2.txt
┗3.dat

とりあえず使ってみる

import glob
import os
file = glob.glob('dirname/*.txt')
print(file)
#['dirname\\1.txt', 'dirname\\2.txt']

フォルダ名とファイル名を分けて取得

print(os.path.split(file[0]))
#('dirname', '1.txt')

print(os.path.split(file[0])[1])
#1.txt

print(os.path.split(file[1]))
#('dirname', '2.txt')

for inで特定の拡張子のファイル名だけ出力

for n in glob.glob('dirname/*.txt'):
    print(os.path.split(n)[1])
#1.txt
#2.txt
for n in glob.glob('dirname/*.dat'):
    print(os.path.split(n)[1])
#3.dat
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0