Wednesday, 15 August 2012

python - Syntax error in a single line if statement -


I am new to Python script on Unix. I am trying to create a directory but this leads to error:

  & gt; & Gt; & Gt; Import OS, sys & gt; & Gt; & Gt; Path = "/ u / home / user / survival" & gt; & Gt; & Gt; If not os.path.exists (path): os.mkdir (path) ... print "directory does not exist." File "& lt; stdin & gt;", line 2 print "directory does not exist. ^ Syntax error: invalid syntax & gt; & Gt; & Gt;  

The error is that you need to exit the secondary prompt . .. Before printing:

  & gt; & Gt; & Gt; If not os.path.exists (path): os.mkdir (path) # Enter one here !!! ... & gt; & Gt; & Gt; The print "directory does not exist. A created directory" does not exist.  

This is the reason why Python Gods have always started avoiding using a line if condition

  & Gt; & Gt; & Gt; If not use os.path.exists (path): ... os.mkdir (path) # indent here !!! ... & gt; & Gt; & Gt; The print "directory does not exist. A created directory" does not exist.  

This is another readable way.

Note : Reading from your code should be a part of print your if block. Please, please use:

  & gt; & Gt; & Gt; If not os.path.exists (path): ... os.mkdir (path) # indent here !!! ... print "directory does not exist. Created one ... ... & gt; & gt; & gt;  

No comments:

Post a Comment