打开两个文件时,with语句中的SyntaxError

时间:2013-04-09 09:40:41

标签: python python-2.7 syntax-error python-2.6

我在Python中由编译器引发'SyntaxError'异常,在下面的语句中随机出现:

with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
                                           ^
SyntaxError: invalid syntax

这里inputFileName是来自我的构建环境的命令行参数,它应该在调用脚本之前创建并显示。以下是示例代码:

try:

with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
       print "do something"
except IOError as e: #(errno,strerror,filename):
        ## Control jumps directly to here if any of the above lines throws IOError.
        sys.stderr.write('problem with \'' + e.filename +'\'.')
        sys.stderr.write(' I/O error({0}): {1}'.format(e.errno, e.strerror) + '.' + '\n')
except:
    print "Unexpected error in generate_include_file() : ", sys.exc_info()[0]

我没有任何线索。请帮帮我。 我正在使用python 2.7。 (python27)

1 个答案:

答案 0 :(得分:4)

分组with语句需要Python 2.7或更高版本。对于早期版本,嵌套语句:

with open(inputFileName, 'rU') as inputFile:
    with open(outputFileName,'w') as outputFile:

您获得的确切错误消息是您在Python 2.6上运行代码的有力证据, 2.7:

$ python2.6
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(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
  File "<stdin>", line 1
    with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
                                               ^
SyntaxError: invalid syntax
>>>

$ python2.7
Python 2.7.3 (default, Oct 22 2012, 06:12:32) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
... 

您无法在任何 Python版本中使用with处理程序对except语句进行分组,您需要使用try: except: with语句代替:

try:
    with open(inputFileName, 'rU') as inputFile, open(outputFileName,'w') as outputFile:
       print "do something"
except IOError as e: #(errno,strerror,filename):
    ## Control jumps directly to here if any of the above lines throws IOError.
    sys.stderr.write("problem with '{}'. ".format(e.filename))
    sys.stderr.write(' I/O error({0}): {1}.\n'.format(e.errno, e.strerror))
except:
    print "Unexpected error in generate_include_file() : ", sys.exc_info()[0]

使用毯子,除了我自己;毯子除了捕获名称,内存和键盘中断异常外,你通常想要退出你的程序。

相关问题