使用`with open ...`

时间:2016-02-06 15:45:16

标签: python python-2.7 with-statement

有几个关于SO的问题似乎与我的问题有关。但是,它们似乎都是由使用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

谢谢!

1 个答案:

答案 0 :(得分:3)

您的layout_marginTop声明后需要:

with