代码之家  ›  专栏  ›  技术社区  ›  Paul D. Waite

如何在python中列出目录的内容?

  •  137
  • Paul D. Waite  · 技术社区  · 15 年前

    _t难,但我有智力障碍。

    8 回复  |  直到 6 年前
        1
  •  200
  •   user85461    15 年前
    import os
    os.listdir("path") # returns list
    
        2
  •  44
  •   maugch    6 年前

    一种方式:

    import os
    os.listdir("/home/username/www/")
    

    Another way :

    glob.glob("/home/username/www/*")
    

    Examples found here .

    这个 glob.glob 上面的方法不会列出隐藏文件。

        3
  •  29
  •   Mark Tolonen    9 年前

    os.walk 如果需要递归,可以使用:

    import os
    start_path = '.' # current directory
    for path,dirs,files in os.walk(start_path):
        for filename in files:
            print os.path.join(path,filename)
    
        4
  •  17
  •   Paul D. Waite    12 年前

    glob.glob os.listdir 会做的。

        5
  •  12
  •   Paul D. Waite    12 年前

    这个 os module 处理所有的事情。

    os.listdir(path)

    返回一个列表,其中包含由path指定的目录中的条目名称。 列表的顺序是任意的。它不包括特殊条目“.”和 “.”即使它们存在于目录中。

    可用性:Unix、Windows。

        6
  •  2
  •   jpyams David Thompson    7 年前

    在python 3.4+中,您可以使用 pathlib 包裹:

    from pathlib import Path
    for path in Path('.').iterdir():
        print(path)
    

    Path.iterdir() 返回一个迭代器,它可以很容易地转换为 list :

    contents = list(Path('.').iterdir())
    
        7
  •  2
  •   Jean-François Fabre    6 年前

    由于python 3.5,您可以使用 os.scandir .

    区别在于它返回文件 条目 没有名字。在一些操作系统(如Windows)上,这意味着您不必 os.path.isdir/file 知道它是不是一个文件,这节省了CPU时间,因为 stat 在Windows中扫描dir时已完成:

    列出目录并打印大于 max_value 字节:

    for dentry in os.scandir("/path/to/dir"):
        if dentry.stat().st_size > max_value:
           print("{} is biiiig".format(dentry.name))
    

    (阅读我的基于性能的广泛答案 here )

        8
  •  1
  •   Heenashree Khandelwal    8 年前

    下面的代码将列出目录和目录中的文件。另一个是os.walk

    def print_directory_contents(sPath):
            import os                                       
            for sChild in os.listdir(sPath):                
                sChildPath = os.path.join(sPath,sChild)
                if os.path.isdir(sChildPath):
                    print_directory_contents(sChildPath)
                else:
                    print(sChildPath)
    
    推荐文章