我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。

也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?


当前回答

但我猜你的真正意图是创建一个文件和其主目录,因为它的内容全部在1命令。

您可以使用 fastcore 扩展到 pathlib: path.mk_write(数据)

from fastcore.utils import Path
Path('/dir/to/file.txt').mk_write('Hello World')

在Fastcore文档中查看更多

其他回答

但我猜你的真正意图是创建一个文件和其主目录,因为它的内容全部在1命令。

您可以使用 fastcore 扩展到 pathlib: path.mk_write(数据)

from fastcore.utils import Path
Path('/dir/to/file.txt').mk_write('Hello World')

在Fastcore文档中查看更多

在 Python 3.4 中,您还可以使用全新 pathlib 模块:

from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
    if not path.parent.exists():
        path.parent.mkdir(parents=True)
except OSError:
    # handle error; you can also catch specific errors like
    # FileExistsError and so on.

在Python中做到这一点的最佳方法

#Devil
import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
    os.makedirs(directory)

试试 os.path.exist 函数

if not os.path.exists(dir):
    os.mkdir(dir)

使用尝试除外,并从 errno 模块的正确错误代码可以摆脱赛车状态,并是跨平台:

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

换句话说,我们试图创建目录,但如果它们已经存在,我们会忽略错误。 另一方面,任何其他错误都会被报告. 例如,如果您提前创建 dir 'a' 并从中删除所有权限,您将获得一个 OSError 提取的 errno.EACCES (Permission denied, error 13)。