2013-10-18 74 views
-1

教程的Python的SyntaxError開放()

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

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

我的代碼,
在蟒蛇2.7.5

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

爲什麼是語法錯誤?

+3

沒有,所以它的代碼的不同部分出了問題。 –

+0

你可以再試一次嗎?對我來說看起來很好 – karthikr

+0

你可以展示一些圍繞該語句的代碼嗎? – Evert

回答

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看到你正在使用的真實版。

+0

啊廢話你是對的。我是用錯誤的python運行它 – ealeon

+0

如果是這樣的話,你可以使用'from __future__ import with_statement'。更好的是升級Python版本。 – Evert