7

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?

L.Bes
  • 73
  • 2

1 Answers1

9

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))
Anish Goyal
  • 2,799
  • 12
  • 17