5.13 获取某个目录下包含的文件列表
- 使用os.listdir()函数来获取某个目录下包含的文件列表
>>> os.listdir('/Users/leosdaydream/ning-dashboard')
['.DS_Store', 'ssh_list', 'fy', 'zsh', 'fonts', 'my_blog']
>>> names = [name for name in os.listdir('/Users/leosdaydream/ning-dashboard') if os.path.isfile(os.path.join('/Users/leosdaydream/ning-dashboard',name))]
>>> names
['.DS_Store']
>>> dirnames = [name for name in os.listdir('/Users/leosdaydream/ning-dashboard') if os.path.isdir(os.path.join('/Users/leosdaydream/ning-dashboard',name))]
>>> dirnames
['ssh_list', 'fy', 'zsh', 'fonts', 'my_blog']
>>>
>>> txtfiles = glob.glob("/Users/leosdaydream/ning-dashboard/ssh_list/*.txt")
>>> txtfiles
['/Users/leosdaydream/ning-dashboard/ssh_list/0519.txt', '/Users/leosdaydream/ning-dashboard/ssh_list/test.txt']
>>> from fnmatch import fnmatch
>>> txtfiles = [name for name in os.listdir("/Users/leosdaydream/ning-dashboard/ssh_list/") if fnmatch(name,'*.txt')]
>>> txtfiles
['0519.txt', 'test.txt']
>>>
- listdir只能拿到目录名,如果想要拿到文件的源数据,我们可以使用os.stat()
>>> import os
>>> import os.path
>>> import glob
>>> txtfiles = glob.glob('*.txt')
>>> txtfiles
['0519.txt', 'test.txt']
>>> name_az_date=[(name,os.path.getsize(name),os.path.getmtime(name)) for name in txtfiles]
>>> for name,size,mtime in name_az_date:
... print(name,size,mtime)
...
0519.txt 1565460 1652969785.2629306
test.txt 697 1653058923.5924325
>>> file_metadata = [(name,os.stat(name)) for name in txtfiles]
>>> for name,metadata in file_metadata:
... print(name,metadata)
...
0519.txt os.stat_result(st_mode=33188, st_ino=8673207752, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1565460, st_atime=1652969936, st_mtime=1652969785, st_ctime=1652969785)
test.txt os.stat_result(st_mode=33188, st_ino=8673349559, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=697, st_atime=1653060175, st_mtime=1653058923, st_ctime=1653058923)
>>>