open()的Python语法错误

时间:2013-10-18 14:48:32

标签: python

教程

http://docs.python.org/2/tutorial/inputoutput.html

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

我的代码,
在python 2.7.5中

with open(filea, 'r') as f:
        ^ SyntaxError: invalid syntax

为什么会出现语法错误?

1 个答案:

答案 0 :(得分:17)

你没有在2.7.5中运行你的代码;你是在早些时候运行它,可能是2.4或2.5。

~$ ~/sys/Python-2.5.6/python
Python 2.5.6 (r256:88840, Jul 12 2012, 12:21:58) 
[GCC 4.6.3] on linux3
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("fred") as f:
<stdin>:1: Warning: 'with' will become a reserved keyword in Python 2.6
  File "<stdin>", line 1
    with open("fred") as f:
            ^
SyntaxError: invalid syntax

添加import sysprint sys.version以查看您正在使用的真实版本。