How do I check whether a file exists without exceptions?

后端 未结 30 1934
北海茫月
北海茫月 2020-11-21 05:07

How do I check if a file exists or not, without using the try statement?

30条回答
  •  不知归路
    2020-11-21 05:28

    Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:

    import pathlib
    p = 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 stuff
    except 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 versions
    import pathlib2 as pathlib
    

提交回复
热议问题