0

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

  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:

任何想法都会受到欢迎。

4

2 回答 2

7

查看它前面的行,会缺少括号或括号。

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

于 2012-09-14T16:06:10.007 回答
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

蟒蛇 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

据我所知,您正在尝试与不支持的 python 2.4 一起使用 open。

于 2012-09-14T17:13:37.503 回答