How do I check whether a file exists without exceptions?

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

    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

提交回复
热议问题