How do I check if a file exists, using Python. without using a try: statement?
You have the os.path.exists function:
import os.path
os.path.exists(file_path)
You can also use
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
Unlike isfile(), exists() will yield True for directories. So depending if you want only plain files or also directories, you'll use isfile() or exists()
>>> print os.path.isfile("/etc/passwd")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/passwd")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
Just to add to the answers - you're almost always better off using the try: open() approach. os.path.exists() only tells you that the file existed at that point. In the tiny interval between that and running code that depends on it, it is possible that someone will have created or deleted the file.
This is a race condition that can often lead to security vulnerabilities. An attacker can create a symlink to an arbitrary file immediately after the program checks no file exists. This way arbitrary files can be read or overwritten with the privilege level your program runs with.
Prefer the try/catch. It's considered better style and avoids race conditions.
Don't take my word for it. There's plenty of support for this theory. Here's a couple:
- Style: Section "Handling unusual conditions" of http://allendowney.com/sd/notes/notes11.txt
- Race condition: http://www.pubbs.net/python/200909/105975/
You could try this:
while(True): if os.path.exists("path\to\file.jpeg"): break