【问题标题】:How to identify whether a file is normal file or directory如何判断一个文件是普通文件还是目录
【发布时间】:2009-06-05 13:47:31
【问题描述】:

如何使用python检查文件是普通文件还是目录?

【问题讨论】:

标签: python


【解决方案1】:

os.path.isdir()os.path.isfile() 应该给你你想要的。看: http://docs.python.org/library/os.path.html

【讨论】:

【解决方案2】:

正如其他答案所说,os.path.isdir()os.path.isfile() 是您想要的。但是,您需要记住,这不是仅有的两种情况。例如,将os.path.islink() 用于符号链接。此外,如果文件不存在,这些都将返回 False,因此您可能还需要检查 os.path.exists()

【讨论】:

【解决方案3】:

Python 3.4 将the pathlib module 引入标准库,它提供了一种面向对象的方法来处理文件系统路径。相关的方法是.is_file().is_dir()

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.is_file()
Out[3]: False

In [4]: p.is_dir()
Out[4]: True

In [5]: q = p / 'bin' / 'vim'

In [6]: q.is_file()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

Pathlib 也可通过the pathlib2 module on PyPi. 在 Python 2.7 上使用

【讨论】:

    【解决方案4】:

    检查是否 文件/目录存在

    os.path.exists(<path>)
    

    检查如果 路径是目录

    os.path.isdir(<path>)
    

    检查如果 路径是文件

    os.path.isfile(<path>)
    

    【讨论】:

      【解决方案5】:

      os.path.isdir('string')
      os.path.isfile('string')

      【讨论】:

        【解决方案6】:
        import os
        
        if os.path.isdir(d):
            print "dir"
        else:
            print "file"
        

        【讨论】:

          【解决方案7】:

          试试这个:

          import os.path
          if os.path.isdir("path/to/your/file"):
              print "it's a directory"
          else:
              print "it's a file"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-09-13
            • 1970-01-01
            • 2011-09-12
            • 2014-05-15
            • 1970-01-01
            相关资源
            最近更新 更多