如何判断一个文件是普通文件还是目录

发布于 2024-07-23 10:45:45 字数 33 浏览 7 评论 0原文

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

How do you check whether a file is a normal file or a directory using python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

呆头 2024-07-30 10:45:45

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

os.path.isdir() and os.path.isfile() should give you what you want. See:
http://docs.python.org/library/os.path.html

红墙和绿瓦 2024-07-30 10:45:45

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

As other answers have said, os.path.isdir() and os.path.isfile() are what you want. However, you need to keep in mind that these are not the only two cases. Use os.path.islink() for symlinks for instance. Furthermore, these all return False if the file does not exist, so you'll probably want to check with os.path.exists() as well.

拥抱影子 2024-07-30 10:45:45

Python 3.4 在标准中引入了pathlib 模块库,它提供了一种面向对象的方法来处理文件系统路径。 相关方法为 .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 也可通过 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():

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 is also available on Python 2.7 via the pathlib2 module on PyPi.

赤濁 2024-07-30 10:45:45
import os

if os.path.isdir(d):
    print "dir"
else:
    print "file"
import os

if os.path.isdir(d):
    print "dir"
else:
    print "file"
缘字诀 2024-07-30 10:45:45
os.path.isdir('string')
os.path.isfile('string')

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

安人多梦 2024-07-30 10:45:45

尝试这个:

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

try this:

import os.path
if os.path.isdir("path/to/your/file"):
    print "it's a directory"
else:
    print "it's a file"
仅此而已 2024-07-30 10:45:45

检查是否文件/目录存在

os.path.exists(<path>)

检查是否路径是目录

os.path.isdir(<path>)

检查 >如果路径是一个文件

os.path.isfile(<path>)

To check if a file/directory exists:

os.path.exists(<path>)

To check if a path is a directory:

os.path.isdir(<path>)

To check if a path is a file:

os.path.isfile(<path>)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文