os.path 模块似乎是所有路径相关函数的默认模块。然而,listdir() 函数是 os 模块的一部分而不是 os.path 模块,即使它接受路径作为其输入.为什么做出这个设计决定?
请您参考如下方法:
我个人发现 os 之间的划分和 os.path有点不一致。根据文档,os.path应该只是使用特定平台路径的模块的别名(即,在 OS X、Linux 和 BSD 上你会得到 posixpath ,在 Windows 或古老的 Mac 上你会得到其他东西)。
>>> import os
>>> help(os)
Help on module os:
NAME
os - OS routines for Mac, NT, or Posix depending on what system we're on.
...
>>> help(os.path)
Help on module posixpath:
NAME
posixpath - Common operations on Posix pathnames.
listdir函数不对路径 本身进行操作,而是对路径标识的目录进行操作。 os.path 中的大部分功能在实际路径上操作,不在文件系统上操作。
这意味着 os.path 中的许多函数是字符串操作函数,os 中的大多数函数是 IO 函数/系统调用。
例子:
os.path.join,os.path.dirname,os.path.splitext, 只是字符串操作函数。os.listdir,os.getcwd,os.remove,os.stat都是系统调用,实际上涉及文件系统。
反例:
-
os.path有exists,getmtime,islink,以及其他基本上是os.stat的包装器,然后触摸文件系统。我认为它们分类错误,但其他人可能不同意。
今日趣事:您不会在库文档的顶层找到这些模块,但您实际上可以导入 os.path 的版本适用于任何平台,而无需在该平台上实际运行。这记录在 os.path 的文档中,
However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:
posixpathfor UNIX-style pathsntpathfor Windows pathsmacpathfor old-style MacOS pathsos2emxpathfor OS/2 EMX paths
你不能用 os 做同样的事情,这没有任何意义。
