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

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


当前回答

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

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。

其他回答

试试 os.path.exist 函数

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

查看 os.makedirs: (它确保完整的路径存在) 要处理可能存在的目录的事实,查找 OSError. (如果存在_ok 是假的(默认情况下),如果目标目录已经存在,则会升起 OSError。

import os
try:
    os.makedirs('./path/to/somewhere')
except OSError:
    pass

我找到了这个Q/A之后我被一些失败和错误我得到,当我在Python的目录工作,我在Python 3工作(在一个Anaconda虚拟环境中的3.5在一个Arch Linux x86_64系统)。

考虑此目录结构:

└── output/         ## dir
   ├── corpus       ## file
   ├── corpus2/     ## dir
   └── subdir/      ## dir

下面是我的实验 / 笔记,提供澄清:

# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist

import pathlib

""" Notes:
        1.  Include a trailing slash at the end of the directory path
            ("Method 1," below).
        2.  If a subdirectory in your intended path matches an existing file
            with same name, you will get the following error:
            "NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:

# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but no file created (os.makedirs creates dir, not files!  ;-)
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# [2] https://docs.python.org/3/library/os.html#os.makedirs

# Uncomment these to run "Method 1":

#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)

# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## works
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## works
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# Uncomment these to run "Method 2":

#import os, errno
#try:
#       os.makedirs(out_dir)
#except OSError as e:
#       if e.errno != errno.EEXIST:
#               raise
# ----------------------------------------------------------------------------

结论:我认为“方法2”更强大。

[1] 我如何安全地创建一张被锁定的目录?

[2] https://docs.python.org/3/图书馆/os.html#os.makedirs

在 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.

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

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

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

在Fastcore文档中查看更多