How do I check whether a file exists without exceptions?

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

    You could try this (safer):

    try:
        # http://effbot.org/zone/python-with-statement.htm
        # 'with' is safer to open a file
        with open('whatever.txt') as fh:
            # Do something with 'fh'
    except IOError as e:
        print("({})".format(e))
    

    The ouput would be:

    ([Errno 2] No such file or directory: 'whatever.txt')

    Then, depending on the result, your program can just keep running from there or you can code to stop it if you want.

提交回复
热议问题