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

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


当前回答

我使用os.path.exists(),这里是一个Python 3脚本可以用来检查是否有一个目录,创建一个如果它不存在,并删除它如果它存在(如果需要)。

它鼓励用户输入目录,并且可以轻松修改。

其他回答

如果您正在写一个文件到一个变量路径,您可以在文件路径上使用此文件,以确保母目录创建。

from pathlib import Path

path_to_file = Path("zero/or/more/directories/file.ext")
parent_directory_of_file = path_to_file.parent
parent_directory_of_file.mkdir(parents=True, exist_ok=True)

工作,即使 path_to_file 是 file.ext (零目录深)。

查看 pathlib.PurePath.parent 和 pathlib.Path.mkdir。

我下载了下面的文章,但这不是完全愚蠢的。

import os

dirname = 'create/me'

try:
    os.makedirs(dirname)
except OSError:
    if os.path.exists(dirname):
        # We are nearly safe
        pass
    else:
        # There was an error on creation, so make sure we know about it
        raise

如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。

你可以使用Megath。

# Create a directory and any missing ancestor directories. 
# If the directory already exists, do nothing.

from distutils.dir_util import mkpath
mkpath("test")    

请注意,它也将创建祖先目录。

它适用于Python 2和3。

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

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

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

在Fastcore文档中查看更多

在创建目录之前,您必须设置完整的路径:

import os,sys,inspect
import pathlib

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"

if not os.path.exists(your_folder):
   pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)

这对我工作,我希望这对你也工作。