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")
LeKhan9
  • 1,300
  • 1
  • 5
  • 15
  • 1
    It's only a syntax error if you aren't using Python 3 or `from __future__ import print_function`. – chepner Nov 13 '18 at 17:35
  • 4
    To make it a little more clear, can you also post the exact error, please? – RafazZ Nov 13 '18 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. – chepner Nov 13 '18 at 17:36
  • https://stackoverflow.com/questions/14461905/python-if-else-short-hand – JR ibkr Nov 13 '18 at 17:39

2 Answers2

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")
chepner
  • 497,756
  • 71
  • 530
  • 681
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 ''
LeKhan9
  • 1,300
  • 1
  • 5
  • 15