Danielok1993 Danielok1993 - 1 year ago 77
Python Question

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

Which one should I use to maximize performance?



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.