How do I check whether a file exists without exceptions?

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

提交回复
热议问题