Python实现文件夹递归拷贝、增量备份与强制删除的完整方案
本文详解Python中文件夹的拷贝与删除实现。针对shutil.copytree无法覆盖已存在文件的限制,提供了支持递归拷贝、增量备份(通过文件大小判断)及强制覆盖的自定义脚本。同时介绍了处理Windows权限问题的文件夹删除方法,并结合任务计划程序实现自动化备份与清理。
本文详细介绍使用Python进行文件夹拷贝和删除的具体实现方法,供读者参考借鉴。
1. 文件夹拷贝方法
from shutil import copytree, ignore_patterns
copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
具体实现参考 shutil.copytree。
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()
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:
copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error(errors)
2. 文件夹删除方法
#! /usr/bash/python # encoding:utf-8 import os import os.path import stat import shutil class DelDir: ''' 删除指定根目录下特定文件夹 ''' def __init__(self, root, dirname): self.root = root self.dirname = dirname def run(self): for r, dirs, files in os.walk(self.root): if self.dirname in dirs: srcDir = os.path.join(r, self.dirname) #更改权限(win7会出现权限问题) os.chmod(srcDir, stat.S_IREAD | stat.S_IWRITE) result = shutil.rmtree(srcDir, False, self.__handler) print "%s" %(srcDir) def __handler(self, function, path, excinfo): ''' 删除出错处理 ''' #更改权限(win7会出现权限问题) os.chmod(path, stat.S_IREAD | stat.S_IWRITE) function(path) print "[Handler] ==> Path:%s \n\tHandler the Error: %s" %(path, excinfo) if __name__ == '__main__': rootdir = r"E:\workspace\minioffice\mini-core\src\main\webapp" # 需要处理的文件夹 rootdir = unicode(rootdir, "utf8") dirname = ".svn" # 删除的文件夹 c = DelDir(rootdir, dirname) c.run()
Python实现文件夹的递归拷贝逻辑
主要目标:
1. 支持多层嵌套文件夹结构,即在需要备份的源文件夹中包含多个子文件夹。
2. 实现增量备份,鉴于文件数量庞大且已存在部分备份数据,仅对新增或变更的文件进行备份,从而提升处理效率。
Python环境安装步骤:
1. 访问 http://www.python.org/getit/ 下载安装包,可选择Python2或Python3版本,其中Python2在兼容性方面表现更佳。
2. 将Python的安装目录(例如D:\Program\Python)添加到系统环境变量Path中,以便全局调用。
脚本编写指南:
虽然Python内置了文件夹拷贝API,但由于其存在诸多限制,无法满足特定需求,因此需要自行实现相关功能。
实现要点包括:
1. 采用递归方式处理多层嵌套文件夹; 2. 完善错误处理机制,需考虑源文件夹不存在等异常情况。
具体脚本代码如下:
###################################################### -*- coding: GBK -*-
# 文件自动备份脚本
# 作者:阿凡提
import os
import shutil
# 设置待备份的源文件夹及存放备份文件的目标文件夹
srcDir = "f:\\src"
dstDir = "f:\\dst"
# 目录递归拷贝函数
def dir_copyTree(src, dst):
names = os.listdir(src)
# 目标文件夹不存在,则新建
if not os.path.exists(dst):
os.mkdir(dst)
# 遍历源文件夹中的文件与文件夹
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
# 是文件夹则递归调用本拷贝函数,否则直接拷贝文件
if os.path.isdir(srcname):
dir_copyTree(srcname, dstname)
else:
if (not os.path.exists(dstname)
or ((os.path.exists(dstname))
and (os.path.getsize(dstname) != os.path.getsize(srcname)))):
print dstname
shutil.copy2(srcname, dst)
except:
error.traceback();
raise
# 备份函数
def dir_backup():
global srcDir
global dstDir
print "源文件夹" + srcDir
print "目标文件夹" + dstDir
print "本次拷贝文件:"
dir_copyTree(srcDir, dstDir)
# 将此句注释则会一闪而过,方便自动备份
raw_input ("备份完成")
# 执行备份函数
dir_backup()
#####################################################
将该脚本与Windows任务计划程序结合,设置定时运行,即可实现自动化的备份功能。
Python文件夹复制的增强版实现
shutil模块主要用于处理文件夹相关操作。其中copytree函数用于复制文件夹,但遗憾的是,如果目标路径中已存在同名文件,该函数会抛出异常,导致操作失败。因此,参考官方帮助文档中的源码进行了修改,使其默认支持文件和文件夹的覆盖操作。
import os
import os.path
import shutil
def copytree(src, dst, symlinks=False):
names = os.listdir(src)
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
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)
else:
if os.path.isdir(dstname):
os.rmdir(dstname)
elif os.path.isfile(dstname):
os.remove(dstname)
shutil.copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except OSError as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error(errors)
if __name__ == '__main__':
copytree('E:/book', 'E:/newbook')
更多关于Python文件与目录操作的技巧,可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》。
希望本文所述的代码与思路能对您的Python程序设计工作有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













