How do I check whether a file exists without exceptions?

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

    It doesn't seem like there's a meaningful functional difference between try/except and isfile(), so you should use which one makes sense.

    If you want to read a file, if it exists, do

    try:
        f = open(filepath)
    except IOError:
        print 'Oh dear.'
    

    But if you just wanted to rename a file if it exists, and therefore don't need to open it, do

    if os.path.isfile(filepath):
        os.rename(filepath, filepath + '.old')
    

    If you want to write to a file, if it doesn't exist, do

    # python 2
    if not os.path.isfile(filepath):
        f = open(filepath, 'w')
    
    # python 3, x opens for exclusive creation, failing if the file already exists
    try:
        f = open(filepath, 'wx')
    except IOError:
        print 'file already exists'
    

    If you need file locking, that's a different matter.

提交回复
热议问题