Python实现删除文件但保留指定文件
2015-06-21 00:00
288 查看
由于给客户的发布版本上客户改动了些代码和图片,我们这边给他们更新publish都是增量更新(开发提供更新指定的文件,我们提取出来给客户进行覆盖更新),但有时需要更新的文件较多导致不得不一个一个的进行查找、替换,工作量大而且容易出错。所以用python写个保留pulish后目录的指定文件、删除其他文件的功能。
代码如下:
import os import os.path def DeleteFiles(path,fileList): for parent,dirnames,filenames in os.walk(path): FullPathList = [] DestPathList = [] for x in fileList: DestPath = path + x DestPathList.append(DestPath) for filename in filenames: FullPath = os.path.join(parent,filename) FullPathList.append(FullPath) for xlist in FullPathList: if xlist not in DestPathList: os.remove(xlist)
代码解释:
1、for parent,dirnames,filenames in os.walk(path): 该for循环用于遍历指定path的父文件夹、文件夹名(不含目录)、文件名
2、
for x in fileList: DestPath = path + x DestPathList.append(DestPath)
该方法两个参数分别是path,filelist。path用来指定publish文件的存放目录,例如:'D:\publish',filelist通过list存放你希望保留的文件及该文件路径,例如:
[r'\1.txt',r'\a\1.txt'],然后将path和filelist拼接起来存放到另一个列表中就是你希望保存文件的完整路径存放在DestPathList中,既['D:\\publish\\1.txt','D:\\publish\\a\\1.txt']
3、
for filename in filenames: FullPath = os.path.join(parent,filename) FullPathList.append(FullPath)
将目录下所有文件的绝对路径存放在列表FullPathList中
4、
for xlist in FullPathList: if xlist not in DestPathList: os.remove(xlist)
遍历FullPathList中元素跟DestPathList中元素进行比对,如果不相同则删除文件
功能虽然简单,但工作中还是比较实用的,故在此留下脚印。
相关文章推荐
- Python os模块学习笔记
- Python实现线程池代码分享
- Python安装第三方库的3种方法
- Python的装饰器模式与面向切面编程详解
- Python中有趣在__call__函数
- Python中实现三目运算的方法
- Python Property属性的2种用法
- python3.3:文本文件读取、处理及保存。小练习
- numpy安装问题
- python编程中的闭包函数
- [Python] Ubuntu12.04LTS
- python curses库
- 零基础项目制学习Python (一)
- python批量处理
- Python的字典的items(), keys(), values()
- [Python]爬虫v0.1
- Python 代码优化基础——判断对象类型
- python下requests模块的安装方法
- python安装lxml,在windows环境下
- Python性能(转)