如何判断一个文件是普通文件还是目录
如何使用python检查一个文件是普通文件还是目录?
How do you check whether a file is a normal file or a directory using python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使用python检查一个文件是普通文件还是目录?
How do you check whether a file is a normal file or a directory using python?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
os.path.isdir() 和 os.path.isfile() 应该给你你想要的。 看:
http://docs.python.org/library/os.path.html
os.path.isdir()
andos.path.isfile()
should give you what you want. See:http://docs.python.org/library/os.path.html
正如其他答案所说, os.path.isdir() 和 os.path.isfile() 是您想要的。 但是,您需要记住,这并不是唯一的两种情况。 例如,使用 os.path.islink() 来表示符号链接。 此外,如果文件不存在,这些都会返回 False,因此您可能还需要检查 os.path.exists() 。
As other answers have said,
os.path.isdir()
andos.path.isfile()
are what you want. However, you need to keep in mind that these are not the only two cases. Useos.path.islink()
for symlinks for instance. Furthermore, these all returnFalse
if the file does not exist, so you'll probably want to check withos.path.exists()
as well.Python 3.4 在标准中引入了
pathlib
模块库,它提供了一种面向对象的方法来处理文件系统路径。 相关方法为.is_file()
和.is_dir()
:Pathlib 也可通过 PyPi 上的 pathlib2 模块。
Python 3.4 introduced the
pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths. The relavant methods would be.is_file()
and.is_dir()
:Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
尝试这个:
try this:
检查是否文件/目录存在:
检查是否路径是目录:
检查 >如果路径是一个文件:
To check if a file/directory exists:
To check if a path is a directory:
To check if a path is a file: