python2.7以下出 NameError: global name 'FileNotFoundError' is not defined的解決方案

原文鏈接:http://blog.csdn.net/waiwai3/article/details/77461276

處理文件不存在使用FileNotFoundError來處理異常


Python版本:2.6


python代碼:

  1. def count_words(filename):
            try:
                    with open(filename) as f_obj:
                            contents = f_obj.read()
            except FileNotFoundError:
                    msg = "Sorry, the file " + filename + " does not exist."
                    print(msg)
            else:
                    words = contents.split()
                    num_words = len(words)
                    print("The file " + filename + " has about " + str(num_words) +" words.")

    filename = 'alice.txt'
    count_words(filename

運行結果:

  1. Traceback (most recent call last):
      File "./count_words.py", line 15, in <module>
        count_words(filename)
      File "./count_words.py", line 6, in count_words
        except FileNotFoundError:
    NameError: global name 'FileNotFoundError' is not define

報錯原因:

FileNotFoundError爲python3使用的文本不存在異常處理方法

在python2.7中使用IOError



修改後的python代碼

  1. #!/usr/bin/env python
    def count_words(filename):
            try:
                    with open(filename) as f_obj:
                            contents = f_obj.read()
            #except FileNotFoundError:
            except IOError:
                    msg = "Sorry, the file " + filename + " does not exist."
                    print(msg)
            else:
                    words = contents.split()
                    num_words = len(words)
                    print("The file " + filename + " has about " + str(num_words) +" words.")

    filename = 'alice.txt'
    count_words(filename)


運行結果:
  1. Sorry, the file alice.txt does not exist

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章