Quantcast
Channel: How do I check whether a file exists without exceptions? - Stack Overflow
Viewing all articles
Browse latest Browse all 47

Answer by Cody Piersall for How do I check whether a file exists without exceptions?

$
0
0

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 stuff

You 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 pathlib2

Then import it as follows:

# Older Python versionsimport pathlib2 as pathlib

Viewing all articles
Browse latest Browse all 47

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>