L.Bes L.Bes -4 years ago 71
Python Question

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

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?

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download