Does, With open() not works with python 2.6

后端 未结 3 826
無奈伤痛
無奈伤痛 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 19:56

    It is the "extended" with statement with multiple context expressions which causes your trouble.

    In 2.6, instead of

    with open(...) as f1, open(...) as f2:
        do_stuff()
    

    you should add a nesting level and write

    with open(...) as f1:
        with open(...) as f2:
            do.stuff()
    

    The docu says

    Changed in version 2.7: Support for multiple context expressions.

    0 讨论(0)
  • 2020-12-11 19:57

    The with open() statement is supported in Python 2.6, you must have a different error.

    See PEP 343 and the python File Objects documentation for the details.

    Quick demo:

    Python 2.6.8 (unknown, Apr 19 2012, 01:24:00) 
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> with open('/tmp/test/a.txt') as f:
    ...     print f.readline()
    ... 
    foo
    
    >>> 
    

    You are trying to use the with statement with multiple context managers though, which was only added in Python 2.7:

    Changed in version 2.7: Support for multiple context expressions.

    Use nested statements instead in 2.6:

    with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1:
        with open("transfer-out/"+exportfileTransferFolder) as f2:
            # f1 and f2 are now both open.
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题