如果某个路径b/c/不存在./a/b/c,shutil.copy("./blah.txt", "./a/b/c/blah.txt")则会抱怨目标不存在.创建目标路径并将文件复制到此路径的最佳方法是什么?
Phi*_*ipp 28
使用os.makedirs创建的目录树.
the*_*ner 21
在使用它之前,我使用与此类似的东西来检查目录是否存在.
if not os.path.exists('a/b/c/'):
os.mkdir('a/b/c')
Run Code Online (Sandbox Code Playgroud)
7yl*_*l4r 17
总结来自给定答案和评论的信息:
对于Python 3.2+ os.makedirs之前copy有exist_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)
我如何使用 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)
| 归档时间: |
|
| 查看次数: |
49536 次 |
| 最近记录: |