亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python中的if語句,簡寫

python中的if語句,簡寫

滄海一幻覺 2021-08-17 10:08:46
我有一個語法錯誤,但我不知道為什么...這是問題所在: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")
查看完整描述

2 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

這個怎么樣?

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



查看完整回答
反對 回復 2021-08-17
?
SMILET

TA貢獻1796條經驗 獲得超4個贊

如果您使用的是 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")


查看完整回答
反對 回復 2021-08-17
  • 2 回答
  • 0 關注
  • 408 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號