使用 `with open...` 的语法错误

SyntaxError using `with open...`

SO 上有几个问题似乎可以解决我的问题。然而,它们似乎都是由使用 pre-2.6 版本的 Python 引起的。这不是这里的情况。感谢任何帮助追查此问题的原因。

当我尝试使用 with open() as f 构造时出现语法错误。

这是代码 (test.py):

#!/usr/bin/env python

import sys
print sys.version

fname = "/tmp/test.txt"

open(fname, 'a').close()

with open(fname, 'a') as fh
  fh.write("test")

这是输出:

$ ./test.py
  File "./test.py", line 10
    with open(fname, 'a') as fh
                              ^
SyntaxError: invalid syntax

Python 正在使用的版本:

$ /usr/bin/env python
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ whereis python
python: /usr/bin/python3.4 /usr/bin/python /usr/bin/python3.4m /usr/bin/python3.3 /usr/bin/python3.3m /usr/bin/python2.7 /usr/lib/python3.4 /usr/lib/python3.3 /usr/lib/python3.5 /usr/lib/python2.7 /etc/python3.4 /etc/python /etc/python3.3 /etc/python2.7 /usr/local/lib/python3.4 /usr/local/lib/python3.3 /usr/local/lib/python2.7 /usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz

我的系统信息:

$ uname -a
Linux ... 4.2.0-27-generic #32-Ubuntu SMP Fri Jan 22 04:49:08 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

谢谢!

您的 with 语句后需要一个 :

with open(fname, 'a') as fh:
  fh.write("test")