相关疑难解决方法(0)

如何在Python中安全地创建嵌套目录?

检查文件目录是否存在的最优雅方法是什么,如果不存在,使用Python创建目录?这是我尝试过的:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

f = file(filename)
Run Code Online (Sandbox Code Playgroud)

不知何故,我错过了os.path.exists(感谢kanja,Blair和Douglas).这就是我现在拥有的:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
Run Code Online (Sandbox Code Playgroud)

是否有"开放"的标志,这会自动发生?

python directory operating-system exception path

3909
推荐指数
28
解决办法
245万
查看次数

什么是神奇的数字,为什么它不好?

什么是神奇的数字?

为什么要避免?

有适合的情况吗?

language-agnostic magic-numbers

489
推荐指数
10
解决办法
24万
查看次数

如何绕过Python 2.7上缺少的`exist_ok`?

在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将无法帮到这里.

python-2.7 os.path

18
推荐指数
2
解决办法
5920
查看次数