Python 递归文件复制到子目录
我需要将所有文件和文件夹复制到当前文件夹的子目录中。这样做的最佳方式是什么?我尝试了下面的代码段,但是失败了,因为如果目标目录已经存在,它就失败了Python 递归文件复制到子目录,python,Python,我需要将所有文件和文件夹复制到当前文件夹的子目录中。这样做的最佳方式是什么?我尝试了下面的代码段,但是失败了,因为如果目标目录已经存在,它就失败了 def copy(d=os.path.curdir): dest = "t" for i in os.listdir(d): if os.path.isdir(i): shutil.copytree(i, dest) else: shutil.copy(i
def copy(d=os.path.curdir):
dest = "t"
for i in os.listdir(d):
if os.path.isdir(i):
shutil.copytree(i, dest)
else:
shutil.copy(i, dest)
我觉得同样的任务可以以更好、更容易的方式完成。我该怎么做呢?查看中的代码,然后稍作调整(例如,尝试:绕过os.makedirs(dst))。您真的需要使用python吗?因为shutil函数无法复制所有文件元数据和组权限。为什么不在linux中尝试内置操作系统命令,如
cp
,在windows中尝试xcopy
您甚至可以尝试从python运行这些命令
import os
os.system("cp file1 file2")
希望这能有所帮助。我永远不会在python上这样做,但我想到了以下解决方案。它看起来并不简单,但应该可以工作并且可以简化(尚未检查,抱歉,现在无法访问计算机):
为了延伸曼努的回答
如果您想使用对操作系统的直接调用,我建议您使用cp-r,因为您似乎需要目录的递归复制。这是我的python递归复制方法版本,似乎可以使用:)
开始复制时,目标子文件夹是否为空?代码段完全有错误。1) 在子目录上而不是在根目录上创建复制树的原因是什么?2)
d
,dest
未被使用。@khachik抱歉,键入得很匆忙。[2] 处理好了。@khachik[1]我觉得将目录/的内容复制到目录/内部目录会导致问题,因为内部目录会试图复制自己。我猜是一个操作系统错误。@Sven是的,最初我试图复制到的子文件夹是空的。嗯,使用os.system是一种好的做法吗?假设我会使用这个,我需要一些bash管道;这将使代码平台依赖。@khachik:for windowsxcopy
可以使用命令@祖宾71:这只是另一个解决方案。我认为,cp
和xcopy
可以更好地复制文件和目录。嗯,我希望避免这种情况,但我想没有其他办法了。谢谢
def copyDirectoryTree(directory, destination, preserveSymlinks=True):
for entry in os.listdir(directory):
entryPath = os.path.join(directory, entry)
if os.path.isdir(entryPath):
entrydest = os.path.join(destination, entry)
if os.path.exists(entrydest):
if not os.path.isdir(entrydest):
raise IOError("Failed to copy thee, the destination for the `" + entryPath + "' directory exists and is not a directory")
copyDirectoryTree(entrypath, entrydest, preserveSymlinks)
else:
shutil.copytree(entrypath, entrydest, preserveSymlinks)
else: #symlinks and files
if preserveSymlinks:
shutil.copy(entryPath, directory)
else:
shutil.copy(os.path.realpath(entryPath), directory)
def copy_all(fr, to, overwrite=True):
fr = os.path.normpath(fr)
to = os.path.normpath(to)
if os.path.isdir(fr):
if (not os.path.exists(to + os.path.basename(fr)) and not
os.path.basename(fr) == os.path.basename(to)):
to += "/" + os.path.basename(fr)
mkdirs(to)
for file in os.listdir(fr):
copy_all(fr + "/" + file, to + "/")
else: #symlink or file
dest = to
if os.path.isdir(to):
dest += "/"
dest += os.path.basename(fr)
if overwrite and (os.path.exists(dest) or os.path.islink(dest)
rm(dest)
if os.path.isfile(fr):
shutil.copy2(fr, dest)
else: #has to be a symlink
os.symlink(os.readlink(fr), dest)
def mkdirs(path):
if not os.path.isdir(path):
os.makedirs(path)
def rm(path):
if os.path.isfile(path) or os.path.islink(path):
os.remove(path)
elif os.path.isdir(path):
for file in os.listdir(path):
fullpath = path+"/"+file
os.rmdir(fullpath)