在Python 3.5中复制时保留目录名
给定以下脚本:在Python 3.5中复制时保留目录名,python,python-3.x,Python,Python 3.x,给定以下脚本: import shutil src = "C:\test" dest = "C:\copied_test" shutil.copytree(src, dest) 此脚本用于将C:\test的内容复制到C:\copied\u test。如何更改脚本,以便将C:\test复制到C:\copied\u test\test,即复制时保留目录名?基于src构建dest目录名,使其成为C:\copied\u test import os # <---- import shutil
import shutil
src = "C:\test"
dest = "C:\copied_test"
shutil.copytree(src, dest)
此脚本用于将
C:\test
的内容复制到C:\copied\u test
。如何更改脚本,以便将C:\test
复制到C:\copied\u test\test
,即复制时保留目录名?基于src
构建dest
目录名,使其成为C:\copied\u test
import os # <----
import shutil
src = r"C:\test"
dest = r"C:\copied_test"
dest = os.path.join(dest, os.path.basename(src)) # <---
shutil.copytree(src, dest)
导入操作系统首先,您的代码是错误的。您应该避开反斜杠(
'C:\\test'
),或者使用为regex设计的这个技巧:r'C:\test'
既然如此,我想dest=“C:\\copied\u test\\test”
不是您想要的答案吧
是否要使用源目录的名称而不必键入它?看看这些方法,它们可以帮助: