user2315506
user2315506

Reputation: 53

Using os.listdir(), see if an object is a file or a directory

Here is the code i wrote:

import os

    for item in os.listdir("C:/"):
        if os.path.isfile(item):
            print(item + " is a file")
        elif os.path.isdir(item):
            print(item + " is a dir")
        else:
            print("Unknown!")

Response:

Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!
Unknown!

Process finished with exit code 0

What i did wrong. I think maybe it is because the folder is locked or encrypted. Please give a hand!

Thanks a lot

Upvotes: 2

Views: 7385

Answers (1)

Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

You need to pass the complete path to isfile() and isdir().

import os


path = "C:"
for item in os.listdir(path):
    item = os.path.join(path, item)
    if os.path.isfile(item):
        print(item + " is a file")
    elif os.path.isdir(item):
        print(item + " is a dir")
    else:
        print("Unknown!")

Upvotes: 2

Related Questions