Python 2.7.1:os.path.isdir() 输出不一致

3 投票
3 回答
1086 浏览
提问于 2025-04-16 12:25

我正在制作一个Python生成ISO文件的应用程序,但在使用os.path.isdir()时遇到了一些奇怪的输出。我是在Arch Linux上运行Python 2.7.1。

我的文件夹结构如下:

/home/andrew/create_iso/Raw_Materials/
/home/andrew/create_iso/Raw_Materials/test_cd/

[andrew@Cydonia Raw_Materials]$ ls -l total 4 drwxr-xr-x 3 andrew andrew 4096 Feb 23 10:20 test_cd

如你所见,test_cd/是一个正常的Linux文件夹。然而,当我运行os.path.isdir()时,结果会根据它是在我的循环中还是我直接写的代码而不同。

import os
>>>for folders in os.listdir('/home/andrew/create_iso/Raw_Materials/'):
...  os.path.isdir(folders)
False

>>>os.path.isdir('/home/andrew/create_iso/Raw_Materials/test_cd')
True

我想也许os.listdir()的输出有问题,但看起来也没什么异常:

>>>os.listdir('/home/andrew/create_iso/Raw_Materials/')
['test_cd']

有没有人知道为什么这两种情况的处理会不同呢?提前谢谢!

3 个回答

1

它在当前目录中寻找 test_cd,而不是在你用 os.listdir 读取的那个目录里。当前目录很可能就是你脚本所在的目录,而这个目录里可能没有叫 test_cd 的东西。os.path.isdir() 在找不到文件时会返回 False,而且当文件存在但不是一个目录时也会返回 False。正如其他人所说的,使用 os.path.join() 来构建一个完整的路径。

4

你需要把文件夹添加到'/home/andrew'这个路径后面。

folder_path = '/home/andrew/create_iso/Raw_Materials/'
for folder in os.listdir(folder_path):
    os.path.isdir(os.path.join(folder_path, folder))
5

'test_cd' 单独来看并不是一个目录。你需要使用 os.path.join 来获取这个目录的绝对路径,然后再用 isdir 来检查它是否真的是一个目录。

撰写回答