分享

Python3

 甘甘灰 2019-12-03

问题

获取文件系统中某个目录下的所有文件列表。

解决方案

使用 os.listdir() 函数来获取某个目录中的文件列表,比如:

import os

file_name = os.listdir('/Users/xz/test')
print(file_name)
['Bath.txt', 'test.py', '2.txt', '1.txt', 'cook.txt']

结果会返回目录中所有文件列表,包括所有文件,子目录,符号链接等等。 如果需要通过某种方式过滤数据,可以考虑结合 os.path 库中的一些函数来使用列表推导。比如:

import os.path

names = [name for name in os.listdir('/Users/xz/test') 
        if os.path.isfile(os.path.join('/Users/xz/test', name))]
        
print(names)
['Bath.txt', 'test.py', '2.txt', '1.txt', 'cook.txt']

字符串的 startswith()endswith() 方法对于过滤一个目录的内容也是很有用的。比如:

pyname = [name for name in os.listdir('/Users/xz/test') if name.endswith('.py')]
print(pyname)
['test.py']

对于文件名的匹配,你可能会考虑使用 globfnmatch 模块。比如:

import glob
pyname = glob.glob('/Users/xz/test/*.py')
print(pyname)
['/Users/xz/test/test.py']

from fnmatch import fnmatch
pyname = [name for name in os.listdir('/Users/xz/test') if fnmatch(name, '*.py')]
print(pyname)
['test.py']

讨论

通过上述的几种方法,均可以获取目录中的文件列表,但是其返回结果只是目录中实体名列表而已。

如果想获取文件的其他元数据,比如文件大小,修改时间等等,需要使用到 os.path 模块中的函数,或os.stat() 函数来收集数据。比如:

# Get file sizes and modification dates
name_sz_dt = [(name, os.path.getsize(name), ar.get(os.path.getmtime(name)).format("YYYY-MM-DD HH:mm:ss")) 
              for name in pyfile]
for name, sizes, date in name_sz_dt:
    print(name, sizes, date)
/Users/xz/test/test.py 214 2018-11-29 14:03:02

# Alternative: Get file metadata
file_metadata = [(name, os.stat(name)) for name in pyfile]
for name, meta in file_metadata:
    print(name, meta.st_size, ar.get(meta.st_mtime).format("YYYY-MM-DD HH:mm:ss"))

/Users/xz/test/test.py 214 2018-11-29 14:03:02

需要注意的是,有时候在处理文件名编码问题时,可能会出现一些问题。 通常,函数 os.listdir()返回的实体列表是根据系统默认的文件名编码进行解码。 但有时候也会遇到一些不能正常解码的文件名。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约