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

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")
添加回答
舉報