这是shutil.copytree 的修改版本,它不创建目录(删除了os.makedirs 调用)。
import os
from shutil import Error, WindowsError, copy2, copystat
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
# os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
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, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.append((src, dst, str(why)))
if errors:
raise Error, errors
使用mock(或Python 3.x 中的unittest.mock),您可以通过将os.makedirs 替换为Mock 对象来暂时禁用os.makedirs(参见unittest.mock.patch):
from shutil import copytree
import mock # import unittest.mock as mock in Python 3.x
with mock.patch('os.makedirs'):
copytree('PlaceB', 'PlaceA')