Python:获取双目录

时间:2015-11-21 04:50:41

标签: python recursion

每次我的代码找到目录时,它都会创建该文件夹,然后在该文件夹中再次创建该文件夹,然后复制这些文件。我不确定为什么会发生这种情况(或者更具体地说,我不确定如何修复它。我确定它与我如何创建目标目录路径有关。)

这是我的复制功能:

def dir_copy(srcpath, dstpath,):
    dstpath = os.path.join(dstpath, os.path.basename(srcpath))
    if not os.path.exists(dstpath):
            os.makedirs(dstpath)
    #tag each file to the source path to create the file path
    for file in os.listdir(srcpath):
        srcfile = os.path.join(srcpath, file)
        dstfile = os.path.join(dstpath, file)
        #if the source file path is a directory, copy the directory
        if os.path.isdir(srcfile):
            try:
                dir_copy(srcfile, dstfile)
            except:
                pass
        else: #if the source file path is just a file, copy the file
            try:
                shutil.copyfile(srcfile, dstfile)
            except:
                pass

2 个答案:

答案 0 :(得分:2)

由于您对dir_copy的递归调用,会出现此问题。我用dstpath

替换了dstfile
def dir_copy(srcpath, dstpath):
    import os, shutil
    dstpath = os.path.join(dstpath, os.path.basename(srcpath))
    print dstpath
    if not os.path.exists(dstpath):
            print("dst path: %s" % dstpath)
            os.makedirs(dstpath)
    #tag each file to the source path to create the file path
    for file in os.listdir(srcpath):
        srcfile = os.path.join(srcpath, file)
        dstfile = os.path.join(dstpath, file)
        #if the source file path is a directory, copy the directory
        if os.path.isdir(srcfile):
            try:
                # modified the recursive call
                dir_copy(srcfile, dstpath)
            except Exception, e:
                print e
                pass
        else: #if the source file path is just a file, copy the file
            try:
                shutil.copyfile(srcfile, dstfile)
            except Exception, e:
                print e
                pass

作为旁注,默默地吃这样的异常是一个坏习惯,因为它会使更复杂的应用程序找到问题的根源变得非常困难。

答案 1 :(得分:1)

如果您只是想以递归方式将src目录复制到dest

from distutils.dir_util import copy_tree
src = "pathToSrc"
dst = "pathToDst"
copy_tree(src, dst)