Pythonを使用してディレクトリ内のファイル数をカウントする方法 質問する

Pythonを使用してディレクトリ内のファイル数をカウントする方法 質問する

ディレクトリ内のファイルのみをカウントするにはどうすればよいでしょうか? 次のようにすると、ディレクトリ自体がファイルとしてカウントされます。

len(glob.glob('*'))

ベストアンサー1

os.listdir()を使用するよりも少し効率的ですglob.glob。ファイル名が通常のファイルであるかどうか (ディレクトリやその他のエンティティではないかどうか) をテストするには、 を使用しますos.path.isfile()

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

おすすめ記事