How do I check whether a file exists without exceptions?

后端 未结 30 1933
北海茫月
北海茫月 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:37

    I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly. Basically, if you are on a non-Windows system, it uses Popen to access find. However, if you are on Windows, it replicates find with an efficient filesystem walker.

    The code itself does not use a try block… except in determining the operating system and thus steering you to the "Unix"-style find or the hand-buillt find. Timing tests showed that the try was faster in determining the OS, so I did use one there (but nowhere else).

    >>> import pox
    >>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
    ['/Users/mmckerns/.python']
    

    And the doc…

    >>> print pox.find.__doc__
    find(patterns[,root,recurse,type]); Get path to a file or directory
    
        patterns: name or partial name string of items to search for
        root: path string of top-level directory to search
        recurse: if True, recurse down from root directory
        type: item filter; one of {None, file, dir, link, socket, block, char}
        verbose: if True, be a little verbose about the search
    
        On some OS, recursion can be specified by recursion depth (an integer).
        patterns can be specified with basic pattern matching. Additionally,
        multiple patterns can be specified by splitting patterns with a ';'
        For example:
            >>> find('pox*', root='..')
            ['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']
    
            >>> find('*shutils*;*init*')
            ['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']
    
    >>>
    

    The implementation, if you care to look, is here: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190

    0 讨论(0)
  • 2020-11-21 05:40

    If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

    If you're not planning to open the file immediately, you can use os.path.isfile

    Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

    import os.path
    os.path.isfile(fname) 
    

    if you need to be sure it's a file.

    Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

    from pathlib import Path
    
    my_file = Path("/path/to/file")
    if my_file.is_file():
        # file exists
    

    To check a directory, do:

    if my_file.is_dir():
        # directory exists
    

    To check whether a Path object exists independently of whether is it a file or directory, use exists():

    if my_file.exists():
        # path exists
    

    You can also use resolve(strict=True) in a try block:

    try:
        my_abs_path = my_file.resolve(strict=True)
    except FileNotFoundError:
        # doesn't exist
    else:
        # exists
    
    0 讨论(0)
  • 2020-11-21 05:40

    Date:2017-12-04

    Every possible solution has been listed in other answers.

    An intuitive and arguable way to check if a file exists is the following:

    import os
    os.path.isfile('~/file.md')  # Returns True if exists, else False
    # additionaly check a dir
    os.path.isdir('~/folder')  # Returns True if the folder exists, else False
    # check either a dir or a file
    os.path.exists('~/file')
    

    I made an exhaustive cheatsheet for your reference:

    #os.path methods in exhaustive cheatsheet
    {'definition': ['dirname',
                   'basename',
                   'abspath',
                   'relpath',
                   'commonpath',
                   'normpath',
                   'realpath'],
    'operation': ['split', 'splitdrive', 'splitext',
                   'join', 'normcase'],
    'compare': ['samefile', 'sameopenfile', 'samestat'],
    'condition': ['isdir',
                  'isfile',
                  'exists',
                  'lexists'
                  'islink',
                  'isabs',
                  'ismount',],
     'expand': ['expanduser',
                'expandvars'],
     'stat': ['getatime', 'getctime', 'getmtime',
              'getsize']}
    
    0 讨论(0)
  • 2020-11-21 05:40
    if os.path.isfile(path_to_file):
        try: 
            open(path_to_file)
                pass
        except IOError as e:
            print "Unable to open file"
    

    Raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. Consider handling missing files with IOErrors. In this situation, an IOError exception will be raised if the file exists but the user does not have read permissions.

    SRC: http://www.pfinn.net/python-check-if-file-exists.html

    0 讨论(0)
  • 2020-11-21 05:41

    Adding one more slight variation which isn't exactly reflected in the other answers.

    This will handle the case of the file_path being None or empty string.

    def file_exists(file_path):
        if not file_path:
            return False
        elif not os.path.isfile(file_path):
            return False
        else:
            return True
    

    Adding a variant based on suggestion from Shahbaz

    def file_exists(file_path):
        if not file_path:
            return False
        else:
            return os.path.isfile(file_path)
    

    Adding a variant based on suggestion from Peter Wood

    def file_exists(file_path):
        return file_path and os.path.isfile(file_path):
    
    0 讨论(0)
  • 2020-11-21 05:43

    You can use the "OS" library of Python:

    >>> import os
    >>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") 
    True
    >>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
    False
    
    0 讨论(0)
提交回复
热议问题