开发者

Python 2.7.1: Inconsistent output from os.path.isdir()

I'm building a Python ISO generation app, and I'm getting some wierd output from os.path.isdir(). I'm running Arch Linux with Python 2.7.1.

I have the following folder structure:

/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

As you can see, test_cd/ is a normal Linux folder. However, when I run os.path.isdir(), I get different results depending on whether it's part of my for loop or whether I hard code it.

import os
>>>for folders in os开发者_如何学Python.listdir('/home/andrew/create_iso/Raw_Materials/'):
...  os.path.isdir(folders)
False

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

I thought maybe there was something wierd in the output I'm getting from os.listdir(), but that also seems to check out:

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

Any idea why it's treating these cases different? Thanks in advance.


'test_cd' by itself is not a directory. You need to do an os.path.join to get the absolute path to the directory, and then call isdir on that.


You need to append folders to the '/home/andrew'... path.

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


It's looking for test_cd in the current directory, not in the directory you're reading with os.listdir. The current directory is probably the same one that contains your script, and it probably contains no item named test_cd. os.path.isdir() returns False when the file is not found, as well as when the file exists but is not a directory. As others have said, use os.path.join() to build a full path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜