LoginSignup
0
1

Pythonで「条件に一致するファイルやディレクトリの一覧を取得する」の動作を確認してみた

Posted at

概要

Pythonで「条件に一致するファイルやディレクトリの一覧を取得する」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

sample1.py
import glob

print(glob.glob('./test/*.txt'))
sample2.py
import glob

print(glob.glob('./test/**/*.txt', recursive=True))
sample3.py
import glob

for name in glob.iglob('./test/**/*.txt', recursive=True):
  print(name)

以下のコマンドを実行しました。

$ mkdir back
$ mkdir img
$ touch book.png
$ touch book.txt
$ touch cup.png
$ touch cup.txt
$ touch pen.png
$ touch pen.txt
$ mkdir test
$ mv back img book.* cup.* pen.* test
$ python3 sample1.py 
['./test/pen.txt', './test/book.txt', './test/cup.txt']
$ touch test/back/2018.txt
$ touch test/back/2019.txt
$ touch test/back/2020.txt
$ mkdir test/back/old
$ touch test/back/old/2017.txt
$ touch test/img/profile.png
$ touch test/img/room.png
$ python3 sample2.py
['./test/pen.txt', './test/book.txt', './test/cup.txt', './test/back/2020.txt', './test/back/2019.txt', './test/back/2018.txt', './test/back/old/2017.txt']
$ python3 sample3.py 
./test/pen.txt
./test/book.txt
./test/cup.txt
./test/back/2020.txt
./test/back/2019.txt
./test/back/2018.txt
./test/back/old/2017.txt

まとめ

何かの役に立てばと。

0
1
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
1