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):
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.