单行if语句中的语法错误

时间:2015-03-16 15:35:05

标签: python

我是UNIX上的python脚本新手。 我正在尝试创建一个目录,但它会导致以下错误:

>>> import os, sys
>>> path = "/u/home/user/exist"
>>> if not os.path.exists(path):os.mkdir(path)
... print "Directory does not exists. created one"



File "<stdin>", line 2
    print "Directory does not exists. created one";
        ^
SyntaxError: invalid syntax
>>>

1 个答案:

答案 0 :(得分:4)

错误是您需要在打印前退出辅助提示...

>>> if not os.path.exists(path):os.mkdir(path) # press an enter here!!!
...
>>> print "Directory does not exists. created one"
Directory does not exists. created one

这就是Python Gods总是要求避免使用单行if条件的原因。使用

>>> if not os.path.exists(path):
...    os.mkdir(path) # Indent here!!!
...
>>> print "Directory does not exists. created one"
Directory does not exists. created one

这是可读方式。

注意:从您的代码中读取,print必须是if块的一部分。所以,请使用:

>>> if not os.path.exists(path):
...    os.mkdir(path) # Indent here!!!
...    print "Directory does not exists. created one"
...
>>>