【问题标题】:How can I list the contents of a directory in Python?如何在 Python 中列出目录的内容?
【发布时间】:2011-02-15 02:29:15
【问题描述】:

不会很难,但我有心理障碍。

【问题讨论】:

    标签: python path


    【解决方案1】:
    import os
    os.listdir("path") # returns list
    

    【讨论】:

    • 并且不传递任何参数将列出 CWD 的内容:os.listdir() = os.listdir('.')
    【解决方案2】:

    一种方式:

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

    Another way:

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

    Examples found here.

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

    自从我多年前最初回答这个问题以来,pathlib 已被添加到 Python 中。我现在列出目录的首选方式通常涉及Path 对象上的iterdir 方法:

    from pathlib import Path
    print(*Path("/home/username/www/").iterdir(), sep="\n")
    

    【讨论】:

    • 当与glob.glob("/home/username/www/.*") 一起使用时,glob.glob 是否会列出隐藏文件(我假设您的意思是 Unix 文件系统上下文中的 .XYZ 文件)?
    • 是的,我的意思是文件以点开头。您提供的示例适用于匹配隐藏文件(并且仅适用于隐藏文件)。
    • 我刚刚导入 glob 并使用了 glob.glob(r'c:\users') 但它只返回 ['c:\\users']
    • @Musixauce3000:你会想做glob.glob(r'c:\users\*')(glob它实际上并没有列出目录,而是扩展了星号等来完成类似的任务)。
    【解决方案3】:

    如果需要递归,可以使用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】:

      glob.globos.listdir 会这样做。

      【讨论】:

      • import glob ENTER glob.glob(r'c:\users') ENTER 似乎只返回['c:\\users']。这是为什么?我想使用 glob.glob 因为正如其他用户所指出的那样,它应该返回目录的内容,同时也忽略隐藏文件。这很重要。
      • 因为你必须用glob指定一个通配符:glob.glob(r'c:\users\*')
      【解决方案5】:

      os module 处理所有这些事情。

      os.listdir(path)

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

      可用性:Unix、Windows。

      【讨论】:

        【解决方案6】:

        在 Python 3.4+ 中,您可以使用新的 pathlib 包:

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

        Path.iterdir()返回一个迭代器,可以很容易地变成list

        contents = list(Path('.').iterdir())
        

        【讨论】:

          【解决方案7】:

          从 Python 3.5 开始,您可以使用os.scandir

          不同之处在于它返回文件 entries 而不是名称。在某些操作系统(如 windows)上,这意味着您不必os.path.isdir/file 即可知道它是否是文件,这样可以节省 CPU 时间,因为在 Windows 中扫描目录时已经完成了stat

          列出目录并打印大于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】:

            下面的代码将列出目录和目录中的文件。另一个是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)
            

            【讨论】:

              猜你喜欢
              • 2019-02-27
              • 2019-01-11
              • 2010-12-16
              • 2015-02-02
              • 2013-12-07
              • 2011-03-18
              • 1970-01-01
              • 1970-01-01
              • 2011-06-10
              相关资源
              最近更新 更多