Python语法错误......不确定原因

时间:2012-09-14 16:04:42

标签: python syntax

我之前使用过如下语句,但是当我尝试使用类似的东西时,它会返回错误....

  File "test.py", line 73
    with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4:
            ^
SyntaxError: invalid syntax

上面一行的语法:

if hostName != "*" and hostIP != "*":
  with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4:

欢迎任何想法。

2 个答案:

答案 0 :(得分:7)

之前查看行,会有一个括号或括号丢失。

那,或者你有一个完全不支持with的python版本,直到python 2.6才会引入语法。

答案 1 :(得分:0)

我在Python 2.4和2.7上都试过了,看起来2.4上也发生了同样的错误,而2.7上却没有。

Python 2.4 - 我确实得到了与你完全相同的错误。

Python 2.4.3 (#1, Nov  3 2010, 12:52:40) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if hostName != "*" and hostIP != "*":
...   with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4:
  File "<stdin>", line 2
    with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4:
            ^
SyntaxError: invalid syntax

Python 2.7

Launching python -O
Python 2.7.2 (default, Apr 17 2012, 22:01:25) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hostIP ='localhost'
>>> hostName = 'abcd'
>>> if hostName != "*" and hostIP != "*":
...   with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4:
...     print 'testing'
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'hostsTxt' is not defined

据我所知,你试图使用open不支持python 2.4。