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

I am creating a Python ISO generation application and I am getting some wierd output from os.path.isdir (). I am 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 regular Linux folder. However, when I run os.path.isdir (), I get different results depending on whether it is part of a for loop or whether I hardcode it.

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

I thought that maybe the output that I get from os.listdir () was something strange, but it also looks like a check:

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

Any idea why she treats these cases differently? Thanks in advance.

+3
3

'test_cd' . os.path.join, , isdir.

+5

"/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))
+4

It searches test_cdin the current directory, not in the directory that you are reading with os.listdir. The current directory is probably the same as your script contains, and it probably does not contain an element with a name test_cd. os.path.isdir()returns Falsewhen the file is not found, and also when the file exists, but is not a directory. As others have said, use os.path.join()to create a complete path.

+1
source

Source: https://habr.com/ru/post/1794253/


All Articles