To check if a directory exists or not

Asked 1 years ago, Updated 1 years ago, 91 views

Using the os module, How do I check if a directory exists or not?

python directory

2022-09-22 22:31

1 Answers

os.path.isdir - check directory only os.path.exists - Check both directories&files

import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

os.path.isdir returns True if a directory exists in the given path. Because isdir follows the symbolic link, both islink() and isdir() can return True for the same path

os.path.exists returns True if a given path exists. Returns False if the path is broken symbolic link. On some platforms, you can return False if you cannot access the file with os.stat() even if the path exists


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.