Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:
import pathlibp = pathlib.Path('path/to/file')if p.is_file(): # or p.is_dir() to see if it is a directory # do stuffYou can (and usually should) still use a try/except block when opening files:
try: with p.open() as f: # do awesome stuffexcept OSError: print('Well darn.')The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:
# installs pathlib2 on older Python versions# the original third-party module, pathlib, is no longer maintained.pip install pathlib2Then import it as follows:
# Older Python versionsimport pathlib2 as pathlib