【发布时间】:2018-03-22 18:36:19
【问题描述】:
我目前在使用 shutil 模块时遇到问题。我正在使用以下函数递归复制文件并覆盖其他文件
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()
if not os.path.isdir(dst): # This one line does the trick
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
shutil.copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except shutil.Error as err:
errors.extend(err.args[0])
except EnvironmentError as why:
errors.append((srcname, dstname, str(why)))
try:
shutil.copystat(src, dst)
except OSError as why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.extend((src, dst, str(why)))
if errors:
raise shutil.Error(errors)
因为我有一些路径比 Windows 上的 PATH_MAX(260 个字符)长,所以我在路径的开头使用了 '\\?\'。有时shutil会返回如下错误:
shutil.Error: [
('\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\distrib\\folders\\file.sch_txt'),
'\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\IMAGE\\schema\\sch_0_15.sch_txt',
"[Errno 22] Invalid argument: '\\\\\\\\?\\\\F:\\\\Jenkins_tests\\\\workspace\\\\team_workspace_tests\\\\sources\\\\master\\\\IMAGE\\\\schema\\\\sch_0_15.sch_txt']`
但是如果我重新启动脚本,我不会有错误,或者另一个文件有错误...
也许我做错了?
【问题讨论】: