有幾個關於SO的問題似乎與我的問題有關。但是,它們都是使用2.6以前版本的Python引起的。這裏不是這種情況。我感謝任何幫助追蹤這個原因。SyntaxError using`with open ...`
當我嘗試使用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
謝謝!
後放 ':' 與開放式(FNAME, 'A')爲FH:你應該刪除這個問題 – AlokThakur
'開(名稱, 'A' ).close()'可以被刪除。通過打開(或嘗試打開)並立即關閉文件,您不會獲得任何收益。 – chepner