Reputation: 64227
I am to list all the files and directories in a directory with os.listdir
and tell them apart reliably. Is it ok to use just os.path.isdir
and consider it's a file if it returns false or should I check os.path.isfile
anyway? Are there cases when os.path.exists(path) and os.path.isdir(path) == os.path.isfile(path)
happens to be true?
Upvotes: 0
Views: 1432
Reputation: 7287
os.path.isdir(path) == os.path.isfile(path)
should never hold in all disk file systems I am aware of, as this should mean that the same object is both a dir and a file. For EXT4 specifically, it is my understanding that an inode can either be a directory or a file.
However, the two functions are not defined as mutually exclusive as that would require an assumption about this being true in all possible filesystems, including future ones, and predictions about that are hard.
Upvotes: 0
Reputation: 374
You should be all good to just use os.path.isdir
. This only looks for if the path that is inputted is a directory. Otherwise, it is okay to assume it is a file. I have tested to see if any cases of whenos.path.exists(path) and os.path.isdir(path) == os.path.isfile(path)
Here are the results.
print(os.path.isdir("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
print(os.path.exists("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
print(os.path.isfile("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
True, True, False
print(os.path.isdir("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
print(os.path.exists("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
print(os.path.isfile("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
False, True, False
print(os.path.isdir("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
print(os.path.exists("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
print(os.path.isfile("C:\\Users\\Kobe Thompson\\Desktop\\Test\\"))
False, False, False
print(os.path.isdir("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
print(os.path.exists("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
print(os.path.isfile("C:\\Users\\Kobe Thompson\\Desktop\\Test\\test"))
False, False, False,
As you can see, there are some cases that can relate both of os.path.isdir and os.path.exists equal to os.path.isfile
Upvotes: 1
Reputation: 26
os.path.isdir and os.path.isfile both are ok! os.path.exists(path) and os.path.isdir(path) == os.path.isfile(path) is always False
Upvotes: 1