如何在 Python 中列出目录的所有文件并将它们添加到list?

发布于 2022-02-17 09:45:59

如何在 Python 中列出目录的所有文件并将它们添加到list?

关注者
0
被浏览
111
1 个回答
  • 面试哥
    面试哥 2022-02-17
    为面试而生,有面试问题,就找面试哥。

    我更喜欢使用该glob模块,因为它可以进行模式匹配和扩展。

    import glob
    print(glob.glob("/home/adam/*"))
    

    它直观地进行模式匹配

    import glob
    # All files and directories ending with .txt and that don't begin with a dot:
    print(glob.glob("/home/adam/*.txt")) 
    # All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
    print(glob.glob("/home/adam/*/*.txt")) 
    

    它将返回一个包含查询文件和目录的列表:

    ['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
    

    请注意,glob忽略以点开头的文件和目录.,因为它们被视为隐藏文件和目录,除非模式类似于.*.

    用于glob.escape转义不属于模式的字符串:

    print(glob.glob(glob.escape(directory_name) + "/*.txt"))
    


  • 面试哥
    面试哥 2022-02-17
    为面试而生,有面试问题,就找面试哥。

    os.listdir()将为您提供目录中的所有内容 -文件目录

    如果您想要文件,您可以使用以下方式过滤os.path

    from os import listdir
    from os.path import isfile, join
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    

    或者您可以使用os.walk()which 将为它访问的每个目录生成两个列表- 为您拆分为文件目录。如果您只想要顶级目录,则可以在第一次产生时中断

    from os import walk
    
    f = []
    for (dirpath, dirnames, filenames) in walk(mypath):
        f.extend(filenames)
        break
    

    或者,更短:

    from os import walk
    
    filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看