如何在python中将包含所有文件的目录从c:\\xxx\yyy复制到c:\\zzz\ [英] how to copy directory with all file from c:\\xxx\yyy to c:\\zzz\ in python

查看:62
本文介绍了如何在python中将包含所有文件的目录从c:\\xxx\yyy复制到c:\\zzz\的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用copytree(src,dst)",但是我不能,因为目标文件夹应该存在.在这里你可以看到我写的一小段代码:

I've been trying to use "copytree(src,dst)", however I couldn't since the destination folder should exists at all.Here you can see the small piece of code I wrote:

def copy_dir(src,dest):
    import shutil
    shutil.copytree(src,dest)

copy_dir('C:/crap/chrome/','C:/test/') 

这是我所预期的错误...

and this is the error I m getting as I expected...

Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\workspace\MMS-Auto\copy.py", line 5, in        <module>
copy_dir('C:/crap/chrome/','C:/test/')   
File "C:\Documents and Settings\Administrator\workspace\MMS-Auto\copy.py", line 3, in copy_dir
shutil.copytree(src,dest)
File "C:\Python27\lib\shutil.py", line 174, in copytree
os.makedirs(dst)
File "C:\Python27\lib\os.py", line 157, in makedirs
mkdir(name, mode)
WindowsError: [Error 183] Cannot create a file when that file already exists:    'C:/test/'

这是我的问题,有没有一种方法可以在不创建自己的 copytree 函数的情况下实现相同的结果?

Here is my question is there a way I could achieve the same result without creating my own copytree function?

提前致谢.

推荐答案

errno 可能的错误.您可以先使用.copytree(),然后在出现错误时使用shutil.copy.

Look at errno for possible errors. You can use .copytree() first, and then when there is error, use shutil.copy.

来自:http://docs.python.org/library/shutil.html#shutil.copytree

如果发生异常,则会引发错误并列出原因.

If exception(s) occur, an Error is raised with a list of reasons.

然后你就可以决定如何处理它并实现你的代码来处理它.

So then you can decide what to do with it and implement your code to handle it.

import shutil, errno

def copyFile(src, dst):
    try:
        shutil.copytree(src, dst)
    # Depend what you need here to catch the problem
    except OSError as exc: 
        # File already exist
        if exc.errno == errno.EEXIST:
            shutil.copy(src, dst)
        # The dirtory does not exist
        if exc.errno == errno.ENOENT:
            shutil.copy(src, dst)
        else:
            raise

关于 .copy():http://docs.python.org/library/shutil.html#shutil.copy

将文件src复制到文件或目录dst.如果 dst 是目录,在中创建(或覆盖)与 src 具有相同基名的文件指定的目录.复制权限位.src 和 dst 是以字符串形式给出的路径名.

Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings.

也许还可以查看<代码>distutils.dir_util.copy_tree

Maybe also look into distutils.dir_util.copy_tree

这篇关于如何在python中将包含所有文件的目录从c:\\xxx\yyy复制到c:\\zzz\的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆