复制没有发生

时间:2013-01-06 05:16:59

标签: python

Guyz - 我遇到这个问题,shutil.copy树认为目录存在,即使它没有..源和目录都是本地的...第一次运行它运行没有错误但内容实际上没有被复制,第二次运行它认为目录已经存在,详情如下..请提供您的输入,如果还有其他方法可以复制除shutil以外的其他方法建议

第一次运行,没有任何错误,但实际上没有复制

  <username:/local/mnt/workspace/username/Scripts>python test.py
    //local/mnt/workspace/loc/04.01.01.00.303_HY11/out
    //local/mnt/workspace/test/out
    copying

第二次重新运行,它认为它认为目录存在

    <username:/local/mnt/workspace/username/Scripts>python test.py
    //local/mnt/workspace/loc/04.01.01.00.303_HY11/out
    //local/mnt/workspace/test/out
    copying
    Traceback (most recent call last):
      File "test.py", line 21, in <module>
        main()
      File "test.py", line 18, in main
        copytree(src,dst)
      File "test.py", line 11, in copytree
        shutil.copytree(s, d)
      File "/pkg/qct/software/python/2.5.2/.amd64_linux26/lib/python2.5/shutil.py", line 110, in copytree
        os.makedirs(dst)
      File "/pkg/qct/software/python/2.5.2/.amd64_linux26/lib/python2.5/os.py", line 171, in makedirs
        mkdir(name, mode)
    OSError: [Errno 17] File exists: '//local/mnt/workspace/test/out'
    <username:/local/mnt/workspace/username/Scripts>

Python代码

import os,shutil

def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        print s
        d = os.path.join(dst, item)
        print d
        if os.path.isdir(s):
            print "copying"
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)
def main ():
    src="//local/mnt/workspace/loc/04.01.01.00.303_HY11"
    dst="//local/mnt/workspace/test"
    copytree(src,dst)

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

尝试此版本,目标目录将自动清除...

import os,shutil,errno

def copytree(src, dst, symlinks=False, ignore=None):
    if os.path.exists(dst):
        shutil.rmtree(dst)

    os.mkdir(dst)

    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        print s + " >> " + d

        if ".git" in s:
            return

        if os.path.isdir(s):
            print "Copying directory..."

            try:
                copytree(s, d, symlinks, ignore)

            except OSError as e: 
                # File already exist
                if e.errno == errno.EEXIST:
                    print "Path exists : " + d
        else:
            shutil.copy2(s, d)

def main ():
    src="//local/mnt/workspace/loc/04.01.01.00.303_HY11"
    dst="//local/mnt/workspace/test"
    copytree(src,dst)

if __name__ == '__main__':
    main()

答案 1 :(得分:0)

请问您为什么不使用shutil.copytree()?如果您确实希望在shutil.copytree()周围设置包装(例如,考虑现有目录),请将您的功能命名为copytree_wrapper()(因为您将copytree与{{1}混合在一起},并且递归不涉及您的shutil.copytree)以下适用于我:

copytree