对于现有文件系统对象,os.path.isfile是否始终与os.path.sdir相反



我要用os.listdir列出一个目录中的所有文件和目录,并可靠地将它们区分开来。如果返回false,只使用os.path.isdir并认为它是一个文件可以吗?或者我应该检查os.path.isfile吗?是否存在os.path.exists(path) and os.path.isdir(path) == os.path.isfile(path)恰好为真的情况?

os.path.isdir和os.path.sfile都可以!os.path.exists(path(和os.path.isdir(path(==os.path.sfile(path(始终为False

只要使用os.path.isdir就可以了。这只会查找输入的路径是否为目录。否则,可以假设它是一个文件。我已经测试过了,看看是否有os.path.exists(path) and os.path.isdir(path) == os.path.isfile(path)的情况。以下是结果。

print(os.path.isdir("C:\Users\Kobe Thompson\Desktop\Test\")) print(os.path.exists("C:\Users\Kobe Thompson\Desktop\Test\")) print(os.path.isfile("C:\Users\Kobe Thompson\Desktop\Test\"))

True,True,False

print(os.path.isdir("C:\Users\Kobe Thompson\Desktop\Test\test"))
print(os.path.exists("C:\Users\Kobe Thompson\Desktop\Test\"))
print(os.path.isfile("C:\Users\Kobe Thompson\Desktop\Test\"))

错误,正确,错误

print(os.path.isdir("C:\Users\Kobe Thompson\Desktop\Test\test"))
print(os.path.exists("C:\Users\Kobe Thompson\Desktop\Test\test"))
print(os.path.isfile("C:\Users\Kobe Thompson\Desktop\Test\"))

错误,错误,错误

print(os.path.isdir("C:\Users\Kobe Thompson\Desktop\Test\test"))
print(os.path.exists("C:\Users\Kobe Thompson\Desktop\Test\test"))
print(os.path.isfile("C:\Users\Kobe Thompson\Desktop\Test\test"))

错误、错误、错误和

正如您所看到的,有一些情况可以将os.path.isdir和os.path.exists与os.path.sfile 相关联

os.path.isdir(path) == os.path.isfile(path)不应该在我所知道的所有磁盘文件系统中都存在,因为这意味着同一个对象既是目录又是文件。具体来说,对于EXT4,我的理解是inode可以是目录也可以是文件。

然而,这两个函数并没有被定义为互斥的,因为这需要假设这在所有可能的文件系统中都是真的,包括未来的文件系统,而且很难预测。

最新更新