我想自动将文件(在目标文件夹中)复制到位于计算机上不同目录中的相应源文件夹(与源具有相同的文件夹结构)的过程...
< br/>这里我在问题中附上了一张截图,以进一步解释我的意思。
非常感谢您的帮助!同时,我也会尝试对此进行更多研究!
最佳答案
这是 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')
关于python - 使用Python自动将文件复制到相应的目标文件夹(shutil.copytree无法按预期工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34100242/