我目前正面临使用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']`
但是如果我重新启动脚本,我将没有错误,或者在另一个文件上出错......
也许我弄错了?
答案 0 :(得分:0)
要解决此问题,我只需要在复制新文件之前删除硬链接。由于我有许多工作区与同一文件有硬链接,因此copyfile函数尝试在其写入模式下打开,如果它与其他工作区同时发生,则可能无法正常工作。