python 递归目录_如何在python中递归复制目录并全部覆盖

看看^{}包,特别是^{}和^{}。您可以使用os.paths.exists()检查文件/路径是否存在。import shutil

import os

def copy_and_overwrite(from_path, to_path):

if os.path.exists(to_path):

shutil.rmtree(to_path)

shutil.copytree(from_path, to_path)

如果dirs已经存在,那么copytree不工作。所以distutils是更好的版本。下面是shutil.copytree的固定版本。它基本上是1-1复制的,除了第一个放在if-else构造后面的os.makedirs():import os

from shutil import *

def copytree(src, dst, symlinks=False, ignore=None):

names = os.listdir(src)

if ignore is not None:

ignored_names = ignore(src, names)

else:

ignored_names = set()

if not os.path.isdir(dst): # This one line does the trick

os.makedirs(dst)

errors = []

for name in names:

if name in ignored_names:

continue

srcname = os.path.join(src, name)

dstname = os.path.join(dst, name)

try:

if symlinks and os.path.islink(srcname):

linkto = os.readlink(srcname)

os.symlink(linkto, dstname)

elif os.path.isdir(srcname):

copytree(srcname, dstname, symlinks, ignore)

else:

# Will raise a SpecialFileError for unsupported file types

copy2(srcname, dstname)

# catch the Error from the recursive copytree so that we can

# continue with other files

except Error, err:

errors.extend(err.args[0])

except EnvironmentError, why:

errors.append((srcname, dstname, str(why)))

try:

copystat(src, dst)

except OSError, why:

if WindowsError is not None and isinstance(why, WindowsError):

# Copying file access times may fail on Windows

pass

else:

errors.extend((src, dst, str(why)))

if errors:

raise Error, errors


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值