【问题标题】:Python function to check whether it is a file or a dirPython函数检查它是文件还是目录
【发布时间】:2014-03-11 14:45:27
【问题描述】:

我已经使用os.listdir()列出了给定路径的所有目录和文件

我想查看列表中的元素是文件还是目录,怎么办?

【问题讨论】:

    标签: python


    【解决方案1】:

    也可以使用内置的 os 库:

    os.path.isdir()
    
    os.path.isfile()
    

    例子:

    import os
    
    root = "C:\\"
    for item in os.listdir(root):
        if os.path.isfile(os.path.join(root, item)):
            print item
    

    【讨论】:

      【解决方案2】:

      使用os.path.isdir

      并始终注意竞争条件。

      【讨论】:

        【解决方案3】:

        使用os.walk可以免费过滤文件和目录,还可以递归处理目录。

        for root, dirs, files in os.walk(root_path):
          process_dirs(dirs)
          process_files(files)
          break # If you only want to process the first level or take a look a the commend below
        

        【讨论】:

        • 但是,如果您只关心顶级目录,这会慢很多并且需要更多工作,for example
        猜你喜欢
        • 2015-06-01
        • 1970-01-01
        • 2011-05-31
        • 2013-03-15
        • 1970-01-01
        • 2018-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多