Martini_geek
Martini_geek

Reputation: 719

Syntax error in a single line if statement

I am new to python scripting on UNIX. I am trying to create a directory but it leads to below error:

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

Upvotes: 0

Views: 1046

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52071

The error is that you need to get out of the secondary prompt ... before printing:

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

This is the reason the Python Gods have always asked to refrain from using the single line if condition. Use

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

This is the more Readable way.

Note : Reading from your code, the print must be a part of your if block. So please, please use:

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

Upvotes: 4

Related Questions