0

I have a syntax error but I don't know why...

Here is the problem:

os.makedirs(nombre) if not existeCarpeta(nombre) else print ("Directorio existente") 

I have a pointer in the print and this is the complete functions:

def existeArchivo(nom): return os.path.isfile(nom) def existeCarpeta(nombre): return os.path.isdir(nombre) def creaCarpeta(nombre): os.makedirs(nombre) if not existeCarpeta(nombre) else print ("Directorio existente") 
4
  • 1
    It's only a syntax error if you aren't using Python 3 or from __future__ import print_function. Commented Nov 13, 2018 at 17:35
  • 4
    To make it a little more clear, can you also post the exact error, please? Commented Nov 13, 2018 at 17:35
  • 2
    However, it's not considered good design to use the conditional expression simply as a replacement for an ordinary if statement, where both the true and false parts are expression statements. Commented Nov 13, 2018 at 17:36
  • stackoverflow.com/questions/14461905/python-if-else-short-hand Commented Nov 13, 2018 at 17:39

2 Answers 2

0

How about this?

print ("Directorio existente") if existeCarpeta(nombre) else os.makedirs(nombre) 

It will print None in the case that the directory does not exist, but it will indeed create it for you.

You can also do this to avoid the None being printed, but its pretty awkward:

s = ("Directorio existente") if existeCarpeta(nombre) else os.makedirs(nombre); print s if s else '' 
Sign up to request clarification or add additional context in comments.

Comments

0

It's only a syntax error if you are using Python 2 and haven't used

from __future__ import print_function 

because you can't use a print statement as part of the conditional expression.

Python 2.7.10 (default, Oct 6 2017, 22:29:07) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> "foo" if False else print("error") File "<stdin>", line 1 "foo" if False else print("error") ^ SyntaxError: invalid syntax >>> from __future__ import print_function >>> "foo" if False else print("error") error 

However, your code is susceptible to a race condition. If some other process creates the directory after you check for it but before you try to create it, your code with raise an error. Just try to create the directory, and catch any exception that occurs as a result.

# Python 2 import errno try: os.makedirs(nombre) except OSError as exc: if exc.errno != errno.EEXISTS: raise print ("Directorio existente") # Python 3 try: os.makedirs(nombre) except FileExistsError: print ("Directorio existente") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.