Python获取目录内容的列表

可以使用os.listdir()函数来获取目录中的文件列表。示例如下:

1
2
>>> import os
>>> names = os.listdir('somedir')

如果省略参数或参数为None,则此时path为当前目录path='.'

这么做会得到原始的目录文件列表,包括所有的文件、子目录、符号链接等。如果要以某种方式筛选数据,可以考虑利用推导式结合os.path模块中各函数来完成。示例如下:

得到目录下所有文件

1
2
3
4
# Get all regular files
>>> import os
>>> filenames = [name for name in os.listdir('somedir')
if os.path.isfile(os.path.join('somedir', name))]

得到目录下文件数

1
2
3
4
# Get numbers of regular files
>>> import os
>>> numbers = len([name for name in os.listdir('somedir')
if os.path.isfile(os.path.join('somedir', name))])

得到目录下所有文件夹

1
2
3
4
# Get all dirs
>>> import os
>>> dirnames = [name for name in os.listdir('somedir')
if os.path.isdir(os.path.join('somedir', name))]

得到目录下文件夹数

1
2
3
4
# Get numbers of dirs
>>> import os
>>> numbers = len([name for name in os.listdir('somedir')
if os.path.isdir(os.path.join('somedir', name))])

得到指定类型(文件扩展名)的文件

字符串的startswith()endswith()方法对于筛选目录中的内容也同样有用。比如:

1
2
>>> import os
>>> pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')]

文件名的匹配

至于文件名的匹配,可能会用到glob或者fnmatch模块。示例如下:

1
2
3
4
5
6
>>> import glob
>>> pyfiles = glob.glob('somedir/*.py')
>>> from fnmatch import fnmatch
>>> pyfiles = [name for name in os.listdir('somedir') if fnmatch(name, '*.py')]
>>>

讨论

得到目录内容的列表很简单,但是这只会带来每个条目的名称。如果想得到一些附加的元数据,比如文件大小、修改日期等。要么使用os.path模块中的其它函数,要么使用os.stat()函数。要得到这些数据,示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os
import os.path
import glob
pyfiles = glob.glob('*.py')
# Get file sizes and modification dates
name_size_date = [(name, os.path.getsize(name), os.path.getmtime(name)) for name in pyfiles]
for name, size, mtime in name_size_date:
print(name, size, mtime)
# Alternative: Get file metadata
file_metadata = [(name, os.stat(name)) for name in pyfiles]
for name, meta in file_metadata:
print(name, meta.st_size, meta.st_mtime)

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄