Testing if a file exists in python

The other day I was asked a question from a friend who was trying to run a pipeline on a bunch of data but wanted to check if a file existed before processing it. In python this is rather straightforward, you could either use the os module and test if a file exists (though this might have problems with speed of accessing files):

import os
print os.path.exists(“test.txt”)

and then test if this is true or false, but you probably want to avoid race conditions. It is also much better programming standard to use a try statement, so something like:

filename = “test.txt”
except IOError as e:
print ‘Does not exist’

nice and then execute your code inside the try statement – or something along those lines with your code.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: