【问题标题】:If statement in python, shorthandpython中的if语句,简写
【发布时间】:2019-04-16 14:47:33
【问题描述】:

我有一个语法错误,但我不知道为什么......

问题来了:

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

我在打印中有一个指针,这是完整的功能:

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

【问题讨论】:

  • 如果您没有使用 Python 3 或 from __future__ import print_function,这只是一个语法错误。
  • 为了更清楚一点,请您也发布确切的错误吗?
  • 但是,将条件表达式简单地用作普通if 语句的替代品并不被认为是好的设计,其中真假部分都是表达式语句。

标签: python shorthand


【解决方案1】:

这个怎么样?

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

如果目录不存在,它会打印None,但它确实会为你创建它。

您也可以这样做来避免打印 None ,但这很尴尬:

s = ("Directorio existente") if existeCarpeta(nombre) else os.makedirs(nombre); print s if s else ''

【讨论】:

    【解决方案2】:

    如果你使用的是 Python 2 并且没有使用过,这只是一个语法错误

    from __future__ import print_function
    

    因为您不能使用print 语句作为条件表达式的一部分。

    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
    

    但是,您的代码容易受到竞争条件的影响。如果其他进程在您检查目录之后但在您尝试创建目录之前创建目录,则您的代码会引发错误。只需尝试创建目录,然后捕获任何因此而发生的异常。

    # 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2012-04-09
      • 2022-01-02
      • 2023-03-23
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多