为shutil.copy文件创建目标路径

jam*_*mes 36 python

如果某个路径b/c/不存在./a/b/c,shutil.copy("./blah.txt", "./a/b/c/blah.txt")则会抱怨目标不存在.创建目标路径并将文件复制到此路径的最佳方法是什么?

Phi*_*ipp 28

使用os.makedirs创建的目录树.

  • 它是`exist_ok`,而不是`exists_ok` (12认同)
  • 请注意,`exists_ok`选项仅出现在Python 3.2+中 (4认同)

the*_*ner 21

在使用它之前,我使用与此类似的东西来检查目录是否存在.

if not os.path.exists('a/b/c/'):
    os.mkdir('a/b/c')
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢使用`os.makedirs`,如果它们不存在则会创建父目录. (2认同)
  • 请注意,这会受到竞争条件的影响(如果其他人或另一个线程在检查和调用 `makedirs` 之间创建了目录)。如果文件夹存在,最好调用 `os.makedirs` 并捕获异常。检查 SoF 以创建目录。 (2认同)

7yl*_*l4r 17

总结来自给定答案和评论的信息:

对于Python 3.2+ os.makedirs之前copyexist_ok=True:

os.makedirs(os.path.dirname(dest_fpath), exist_ok=True)
shutil.copy(src_fpath, dest_fpath)
Run Code Online (Sandbox Code Playgroud)

对于os.makedirs捕获后的python <3.2 IOError并再次尝试复制:

try:
    shutil.copy(src_fpath, dest_fpath)
except IOError as io_err:
    os.makedirs(os.path.dirname(dest_fpath))
    shutil.copy(src_fpath, dest_fpath)
Run Code Online (Sandbox Code Playgroud)

虽然您可以更明确地检查errno和/或检查路径exists之前makedirs,恕我直言,这些片段在简单性和功能性之间取得了很好的平衡.


Mr_*_*s_D 13

EAFP方式,避免比赛和不需要的系统调用:

import errno
import os
import shutil

src = "./blah.txt"
dest = "./a/b/c/blah.txt"
# with open(src, 'w'): pass # create the src file
try:
    shutil.copy(src, dest)
except IOError as e:
    # ENOENT(2): file does not exist, raised also on missing dest parent dir
    if e.errno != errno.ENOENT:
        raise
    # try creating parent directories
    os.makedirs(os.path.dirname(dest))
    shutil.copy(src, dest)
Run Code Online (Sandbox Code Playgroud)


joh*_*son 11

对于 3.4/3.5+,您可以使用pathlib

Path.mkdir(mode=0o777,parents=False,exist_ok=False)


因此,如果可能需要创建多个目录并且它们可能已经存在:

pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)


pet*_*erb 9

我如何使用 split 将目录从路径中取出

dir_name, _ = os.path.split("./a/b/c/blah.txt")
Run Code Online (Sandbox Code Playgroud)

然后

os.makedirs(dir_name,exist_ok=True)
Run Code Online (Sandbox Code Playgroud)

最后

shutil.copy("./blah.txt", "./a/b/c/blah.txt")
Run Code Online (Sandbox Code Playgroud)