我是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
>>>
答案 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"
...
>>>