Reputation: 359
Which one should I use to maximize performance? os.path.isfile(path)
or open(path)
?
Upvotes: 2
Views: 5829
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
Reputation: 15028
Mike has shown that isfile()
is faster, but there are two more things to consider:
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.Both these two points suggest you might be better off using open()
unless you are really really pressed for performance.
Upvotes: 3
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