views:

39668

answers:

9

How do I check if a file exists, using Python. without using a try: statement?

A: 

@if os.path.exists(filename):

Paul
+3  A: 

os.path.exists(filename)

benefactual
You'll need an 'import os', of course.
emk
Indeed you will.
benefactual
+27  A: 

You have the os.path.exists function:

import os.path
os.path.exists(file_path)
PierreBdR
+64  A: 

You can also use

import os.path
os.path.isfile(fname)

if you need to be sure it's a file.

rslite
It should be noted, like in Brian's answer below, that this way of checking the file can lead to a potential security vulnerabilities.
Zxaos
+3  A: 

Additionally, os.access().

zgoda
+22  A: 

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
bortzmeyer
+44  A: 

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.

Brian
+4  A: 

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:

pkoch
A: 

You could try this:

while(True): if os.path.exists("path\to\file.jpeg"): break

Sandesh