Exit gracefully if file doesn't exist

前端 未结 2 2045
感动是毒
感动是毒 2021-02-07 00:12

I have following script in Python 3.2.3:

try:
    file = open(\'file.txt\', \'r\')
except IOError:
    print(\'There was an error opening the file!\')
    sys.ex         


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-07 00:37

    Using sys.exit() is fine. If you're that concerned with output, you can always add an extra try/except block within your error handling section to catch the SystemExit and stop it from being directed to console output.

    try:
        file = open('file.txt', 'r')
    except IOError:
        try:
            print('There was an error opening the file!')
            sys.exit()
        except SystemExit:
            #some code here that won't impact on anything
    

提交回复
热议问题