Does, With open() not works with python 2.6

后端 未结 3 825
無奈伤痛
無奈伤痛 2020-12-11 19:15

I am trying to use \"With open()\" with python 2.6 and it is giving error(Syntax error) while it works fine with python 2.7.3 Am I missing something or some import to make m

3条回答
  •  独厮守ぢ
    2020-12-11 20:07

    The with open() syntax is supported by Python 2.6. On Python 2.4 it is not supported and gives a syntax error. If you need to support PYthon 2.4, I would suggest something like:

    def readfile(filename, mode='r'):
        f = open(filename, mode)
        try:
            for line in f:
                yield f
        except e:
            f.close()
            raise e
        f.close()
    
    for line in readfile(myfile):
        print line
    

提交回复
热议问题