How do I check if a file exists or not, without using the try statement?
Unlike isfile(), exists() will return True
for directories. So depending on if you want only plain files or also directories, you'll use isfile()
or exists()
. Here is some simple REPL output:
>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False