作者:赵浩民奕君 | 来源:互联网 | 2023-01-28 16:20
在Python 2.7 os.makedirs()
上缺少exist_ok
.这仅适用于Python 3.
我知道这是一项有效的工作:
try:
os.makedirs(settings.STATIC_ROOT)
except OSError as e:
if e.errno != errno.EEXIST:
raise
我可以创建一个自定义my_make_dirs()
方法并使用它,而不是os.makedirs()
,但这不是很好.
如果你被迫支持Python 2.7,最诡计多端的工作是什么?
AFAIK python-future或者6将无法帮到这里.
1> kichik..:
解决它的一种方法是使用pathlib.它有一个Python 2的后端及其mkdir()
功能支持exist_ok
.
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path # python 2 backport
Path(settings.STATIC_ROOT).mkdir(exist_ok=True)
为`os.mkdirs`设置`parents = True`
2> Pat Myron..:
You could call makedirs() after checking that the path does not exist:
import os
if not os.path.exists(path):
os.makedirs(path)