How do I check whether a file exists without exceptions?

后端 未结 30 1859
北海茫月
北海茫月 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: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']}
    

提交回复
热议问题