gue*_*tli 18 python-2.7 os.path
在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
Run Code Online (Sandbox Code Playgroud)
我可以创建一个自定义my_make_dirs()方法并使用它,而不是os.makedirs(),但这不是很好.
如果你被迫支持Python 2.7,最诡计多端的工作是什么?
AFAIK python-future或者6将无法帮到这里.
kic*_*hik 15
解决它的一种方法是使用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)
Run Code Online (Sandbox Code Playgroud)
Pat*_*ron 11
You could call makedirs() after checking that the path does not exist:
import os
if not os.path.exists(path):
os.makedirs(path)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5920 次 |
| 最近记录: |