for item in os.listdir("/root"):
if os.path.isfile(item):
print(item + "is a file")
elif os.path.isdir(item):
print(item + "is a dir")
else:
print("Unknown")
According to the for
loop, you are trying to check every file from the /root directory, not from the current one. But os.listdir("/root)
returns only the filenames of files that are in the /root directory without their full paths (e.g. "my_file.txt" instead of "/root/my_file.txt"). And os.path.isfile(...)
and os.path.isdir(...)
require the full paths as their args. So, when you call os.path.isfile(item)
or os.path.isdir(item)
it checks whether the item exists in the current directory, not the /root directory.
Use os.path.join(path, *paths)
to get the full paths for your items, store it in the full_path
variable inside the loop and throw it to the os.path.isdir(...)
and os.path.isfile(...)
instead of the item
.
Here is an example:
for item in os.listdir("/root"):
full_path = os.path.join("/root", item)
if os.path.isfile(full_path):
print(item + " is a file")
elif os.path.isdir(full_path):
print(item + " is a dir")
else:
print("Unknown")