Danielok1993
Danielok1993

Reputation: 359

checking if file exists: performance of isfile Vs open(path)

Which one should I use to maximize performance? os.path.isfile(path) or open(path)?

Upvotes: 2

Views: 5829

Answers (3)

pypat
pypat

Reputation: 1116

Afaik isfile() will be faster while open(path) is more secure, in the sence that if open() is able to actually open the file, you can be sure it's there.

Upvotes: 0

kqr
kqr

Reputation: 15028

Mike has shown that isfile() is faster, but there are two more things to consider:

  1. isfile() only tests if a file exists -- it doesn't tell you anything about read or write permissions! It is very rare to just want to know whether or not a file exists, you often want to test if you can do something with it. open() will tell you this.
  2. Pythonic code generally prefers an EAFP (Easier to Ask Forgiveness than Permission) style, where you try to do things and catch exceptions if you can't. (The opposite is LBYL -- Look Before You Leap, which is common in Java and C, among other languages.)

Both these two points suggest you might be better off using open() unless you are really really pressed for performance.

Upvotes: 3

Mike Müller
Mike Müller

Reputation: 85492

Testing helps. os.path.isfile is quite a bit faster than open:

In [475]: %timeit open('test_test.txt')
10000 loops, best of 3: 47.9 us per loop

In [476]: %timeit os.path.isfile('test_test.txt')
100000 loops, best of 3: 6.21 us per loop

But look at the run times. You need to open or check for a lot of files to have any practical impact on total run time for most applications.

Upvotes: 7

Related Questions