开发者社区 问答 正文

获取文件夹中的文件列表

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

展开
收起
哦哦喔 2020-04-17 12:26:58 1082 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • 使用 os.listdir() 函数来获取某个目录中的文件列表:
    
    import os
    names = os.listdir('somedir')
    结果会返回目录中所有文件列表,包括所有文件,子目录,符号链接等等。 如果你需要通过某种方式过滤数据,可以考虑结合 os.path 库中的一些函数来使用列表推导。比如:
    
    import os.path
    
    # Get all regular files
    names = [name for name in os.listdir('somedir')
            if os.path.isfile(os.path.join('somedir', name))]
    
    # Get all dirs
    dirnames = [name for name in os.listdir('somedir')
            if os.path.isdir(os.path.join('somedir', name))]
    字符串的 startswith() 和 endswith() 方法对于过滤一个目录的内容也是很有用的。比如:
    
    pyfiles = [name for name in os.listdir('somedir')
                if name.endswith('.py')]
    对于文件名的匹配,你可能会考虑使用 glob 或 fnmatch 模块。比如:
    
    import glob
    pyfiles = glob.glob('somedir/*.py')
    
    from fnmatch import fnmatch
    pyfiles = [name for name in os.listdir('somedir')
                if fnmatch(name, '*.py')]
    
    2020-04-17 12:27:07 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等