gpt4 book ai didi

python - (distutil + shutil) * 复制树 =?

转载 作者:太空狗 更新时间:2023-10-30 01:17:09 25 4
gpt4 key购买 nike

我想要 shutil 的 copytree 函数提供的忽略模式。我希望 src 树替换 dest 目录中的所有现有文件/文件夹,如 distutil.dir_util.copy_tree。

我是一个相当新的 Python 用户,似乎找不到任何关于此的帖子。

最佳答案

我早就想说这个了,但我没有说。 http://docs.python.org/library/shutil.html有一个版本的copytree函数。我查看了它是否会替换现有文件,据我所知,它会覆盖现有文件,但如果任何目录已经存在,它就会失败。由于 os.mkdirs 如果目录已经存在则失败。

所需的导入:

import os
import os.path
import shutil

http://code.activestate.com/recipes/82465-a-friendly-mkdir/ 获取 _mkdir (那里的一位评论者提到 os.mkdirs 具有大部分相同的行为,但没有注意到 _mkdir 如果已经创建任何目录则不会失败存在)

def _mkdir(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
_mkdir(head)
#print "_mkdir %s" % repr(newdir)
if tail:
os.mkdir(newdir)

尽管它不像 os.mkdirs 那样采用 mode 参数,但 copytree 不使用它,因此不需要它.

然后更改 copytree 以调用 _mkdir 而不是 os.mkdirs:

def copytree(src, dst, symlinks=False):
"""Recursively copy a directory tree using copy2().

The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.

If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied.

XXX Consider this example code rather than the ultimate tool.

"""
names = os.listdir(src)
# os.makedirs(dst)
_mkdir(dst) # XXX
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks)
else:
shutil.copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass

关于python - (distutil + shutil) * 复制树 =?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7545299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com