Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between './' and '../' when using os.path.isdir()?

Tags:

python

os.path

I'm new to python. And something is confusing me today. Under the path c:\python\, there are several folds. I edit a python script under this path, and run the code:

for dir_name in os.listdir("./"):
        print dir_name
        print os.path.isdir(dir_name)

It prints:

Daily
True
renafile.py
False
script
True

But when I put the script in fold Daily which is under the path C:\python\,and run code:

for dir_name in os.listdir("../"):
        print dir_name
        print os.path.isdir(dir_name)

It prints:

Daily
False
renafile.py
False
script
False

Did they have the difference?

like image 233
L.Bes Avatar asked Mar 23 '17 07:03

L.Bes


People also ask

What is the difference between OS path ISDIR and OS path exists?

os.path.exists will also return True if there's a regular file with that name. os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory. Show activity on this post. Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False.

What is the difference between ISDIR () and exists () in Python?

Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases. Show activity on this post. os.path.isdir () checks if the path exists and is a directory and returns TRUE for the case.

How to check if a path is an existing directory Python?

os.path.isdir () method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True. path: A path-like object representing a file system path.

What is the use of OS path in Python 2?

2. os.path.dirname (path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name. 3. os.path.isabs (path) : It specifies whether the path is absolute or not.


1 Answers

It was returning false because when you call isdir with a folder name, python looks for that folder in the current directory - unless you provide an absolute path or a relative path.

Since you are listing files in "../", you should call isdir like so:

print os.path.isdir(os.path.join("../", dir_name))

You may want to modify your code to:

list_dir_name = "../"
for dir_name in os.listdir(list_dir_name):
  print dir_name
  print os.path.isdir(os.path.join(list_dir_name, dir_name))
like image 199
Anish Goyal Avatar answered Nov 03 '22 20:11

Anish Goyal