4
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python]フォルダ内のファイルを取得する方法

Last updated at Posted at 2015-12-25

python でフォルダ内のファイルを取得するにはglobを使用する

test1フォルダ内に下記のファイルがあるとき

test1.log
test2.log
test3.log
test1.txt
test2.txt
test3.txt
test4.txt
test10.txt
test20.txt
test30.txt

すべてのファイルを取得する

In [1]: import glob

In [2]: glob.glob('./test1/*')
Out[2]: 
['./test1/test2.log',
 './test1/test20.txt',
 './test1/test1.txt',
 './test1/test2.txt',
 './test1/test10.txt',
 './test1/test30.txt',
 './test1/test3.log',
 './test1/test3.txt',
 './test1/test4.txt',
 './test1/test1.log']

拡張子txtだけを取得する

In [3]: glob.glob('./test1/*.txt')
Out[3]: 
['./test1/test20.txt',
 './test1/test1.txt',
 './test1/test2.txt',
 './test1/test10.txt',
 './test1/test30.txt',
 './test1/test3.txt',
 './test1/test4.txt']

testのあとの数字が2桁のファイルを取得する

In [4]: glob.glob('./test1/test[0-9][0-9].*')
Out[4]: ['./test1/test20.txt', './test1/test10.txt', './test1/test30.txt']
4
16
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
4
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?