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?
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With