python 提取文件的小程序


Posted in Python onJuly 29, 2009

以前提取这些文件用的是一同事些的批处理文件;用起来不怎么顺手,刚好最近在学些python,所有就自己动手写了一个python提取文件的小程序;
1、原理
提取文件的原理很简单,就是到一个指定的目录,找出最后修改时间大于给定时间的文件,然后将他们复制到目标目录,目标目录的结构必须和原始目录一致,这样工程人员拿到后就可以直接覆盖整个目录;
2、实现
为了程序的通用,我定义了下面的配置文件
config.xml

<?xml version="1.0" encoding="utf-8"?> 
<config> 
    <srcdir>E:\temp\home\cargill</srcdir> 
    <destdir>E:\temp\dest\cargill</destdir> 
    <notinclude> 
        <dirs> 
            <dir>E:\temp\home\cargill\WEB-INF\lib</dir> 
            <dir>E:\temp\home\cargill\static\cargill\report</dir> 
        </dirs> 
        <files> 
            <file>E:\temp\home\cargill\WEB-INF\classes\myrumba.xml</file> 
            <file>E:\temp\home\cargill\META-INF\context.xml</file> 
        </files> 
    </notinclude> 
    <inittime>2008-10-11 13:15:22</inittime> 
    <rardir>C:\Program Files\WinRAR</rardir> 
</config>

其中
<srcdir>:原始目录,即我们tomcat的发布目录;
<destdir>:文件复制到得目标目录;
<notinclude>:需要忽略的文件夹和文件,具体需要忽略的内容在其子节点中定义,这里不在解释;
<inittime>:这个是初始化需要提取的时间点,在这之后的才会提取,此处需要说明,后来在使用中,我增加了一个功能,就是每次提取完会自动将本次提取时间记录到一个文本文件C_UPGRADETIME.txt中,这就省去每次设置这个值的烦恼,只有C_UPGRADETIME.txt为空或者不存在时,才会用到这个值;
<rardir>:rar压缩程序的地址;
下面是读取配置文件的类:
config.py
''' 
Created on Mar 3, 2009 
@author: alex cheng 
''' 
from xml.dom.minidom import parse, parseString 
import datetime 
import time 
class config(object): 
''' 
config.xml 
''' 
def __init__(self, configfile): 
''' 
configfile:config files 
''' 
dom = parse(configfile) 
self.config_element = dom.getElementsByTagName("config")[0] 
def getSrcDir(self): 
''' 
return the <srcdir> element value of self.config_element 
''' 
srcDir = self.config_element.getElementsByTagName("srcdir")[0] 
return self.getText(srcDir.childNodes) 
def getDestDir(self): 
''' 
return the <destdir> element value of self.config_element 
''' 
destDir = self.config_element.getElementsByTagName("destdir")[0] 
return self.getText(destDir.childNodes) 
def getNotIncludeDirs(self): 
''' 
return a list, it's the <dir> element values of self_config_element 
''' 
notinclude_dirs = self.config_element.getElementsByTagName("dir") 
dirList = [] 
for node in notinclude_dirs: 
dir = self.getText(node.childNodes) 
if dir != '': 
dirList.append(dir) 
return dirList 
def getNotIncludeFiles(self): 
''' 
return a list, it's the <file> element values of self.config_element 
''' 
notinclude_files = self.config_element.getElementsByTagName("file") 
fileList = [] 
for node in notinclude_files: 
file = self.getText(node.childNodes) 
if file != '': 
fileList.append(file) 
return fileList 
def getText(self, nodeList): 
''' 
return the text value of the nodeList node 
''' 
rc = '' 
for node in nodeList: 
if node.nodeType == node.TEXT_NODE: 
rc = rc + node.data 
return rc 
def getInitTime(self): 
''' 
return a datetime object,it's the <inittime> element value of self.config_element 
''' 
initTime = self.config_element.getElementsByTagName("inittime")[0] 
timeStr = self.getText(initTime.childNodes) 
dt = datetime.datetime.strptime(timeStr, "%Y-%m-%d %H:%M:%S") 
fdt = time.mktime(dt.utctimetuple()) 
return fdt 
def getWinRarDir(self): 
''' 
return the value of <rardir> element value 
''' 
rardir = self.config_element.getElementsByTagName('rardir')[0] 
return self.getText(rardir.childNodes) 
if __name__ == '__main__': 
c = config('config.xml') 
home = c.getSrcDir() 
print('home is ', home) 
dest = c.getDestDir() 
print('dest is ', dest) 
dirlist = c.getNotIncludeDirs() 
print('not include directory is:') 
for n in dirlist: 
print(n) 
filelist = c.getNotIncludeFiles() 
print('not include files is:') 
for n in filelist: 
print(n) 
inittime = c.getInitTime() 
print('inittime is', inittime) 
rardir = c.getWinRarDir() 
print(rardir)

下面是程序的主体:
fetchfile.py
''' 
Created on Mar 3, 2009 
@author: alex cheng 
''' 
from config import config 
from os import chdir, listdir, makedirs, system, walk, remove, rmdir, unlink, \ 
removedirs, stat, getcwd 
from os.path import abspath, isfile, isdir, join as join_path, exists 
from shutil import copy2 
from sys import path 
import datetime 
import re 
import time 
def getdestdir(dir): 
''' 
return the dest directory name; 
it's named by date,for example 20090101; if 20090101 has exist the return 20090101(1),if 20090101(1) has exist also, 
then return 20090101(2), and then... 
''' 
today = datetime.datetime.today() 
strtoday = today.strftime('%Y%m%d') 
dr = join_path(dir, strtoday) 
tmp = dr 
index = 0 
while isdir(tmp): 
tmp = dr 
index = index + 1 
tmp = tmp + '(' + '%d' % index + ')' 
return tmp 
def fetchFiles(srcdir, destdir, ignoredirs, ignorefiles, lasttime=time.mktime(datetime.datetime(2000, 1, 1).utctimetuple())): 
''' 
fetch files from srcdir(source directory) to destdir(dest directory) ignore the notcopydires(the ignore directory list) 
and notcopyfiles(the ignore file list), and the file and directory's modify time after the lasttime 
''' 
chdir(srcdir) # change the current directory to the srcdir 
dirs = listdir('.') # get all files and directorys in srcdir, but ignore the "." and ".." 
dirlist = [] # save all directorys in srcdir 
for n in dirs: 
if isdir(n): 
dirlist.append(n) 
for subdir in dirlist: 
exist = False 
for ignoredir in ignoredirs: 
if join_path(srcdir, subdir) == ignoredir: 
exist = True 
break 
if exist: 
continue 
fetchFiles(join_path(srcdir, subdir), join_path(destdir, subdir), ignoredirs, ignorefiles, lasttime) 
copyfiles(srcdir, destdir, ignorefiles, lasttime) 
def copyfiles(srcdir, destdir, ignorefiles, lasttime): 
''' 
copy the files from srcdir(source directory) to destdir(dest directory, if dest directory not exist then create is) 
ignore the notcopyfiles(the ignore file list) and the file's modify time must after lasttime 
''' 
chdir(srcdir) 
files = filter(isfile, listdir('.')) 
for file in files: 
if isdir(file): # ignore the directory 
continue 
lastmodify = stat(file).st_mtime 
if lastmodify < lasttime: 
continue 
exist = False 
for ignorefile in ignorefiles: 
if join_path(srcdir, file) == ignorefile: 
exist = True 
if not exist: 
if isdir(destdir) is False: 
try: 
makedirs(destdir) 
print('success create directory:', destdir) 
except: 
raise Exception('failed create directory: ' + destdir) 
try: 
copy2(file, join_path(destdir, file)) 
print('success copy file from', join_path(srcdir, file), 'to', join_path(destdir, file)) 
except: 
raise Exception('failed copy file from ' + join_path(srcdir, file) + ' to ' + join_path(destdir, file)) def tarfiles(dir, todir, winrardir, tarfilename): 
''' 
tar all files in dir(a directory) to todir(dest directory) and the tar file named tarfilename 
''' 
if isdir(dir) is False: 
print('the directory', dir, 'not exist') 
return 
chdir(dir) 
commond = '\"' + winrardir + '\\rar.exe\" a -r ' + todir + '\\' + tarfilename + ' *.*' 
print(commond) 
if system(commond) == 0: 
print('success tar files') 
else: 
print('failed tar files') 
def removeDir(dir_file, currentdir): 
''' 
delete the dir_file 
''' 
if isdir(currentdir) is False: 
print() 
return 
chdir(currentdir) 
if not exists(dir_file): 
return 
if isdir(dir_file): 
for root, dirs, files in walk(dir_file, topdown=False): 
for name in files: 
remove(join_path(root, name)) 
for name in dirs: 
rmdir(join_path(root, name)) 
rmdir(dir_file) # remove the main dir 
else: 
unlink(dir_file) 
return 
def getlasttime(): 
''' 
get last modify time from txt files 
''' 
try: 
mypath = abspath(path[0]) #get current path 
file = join_path(mypath, 'C_UPGRADETIME.txt') 
if isfile(file) is False: 
return 0 
f = open(join_path(mypath, 'C_UPGRADETIME.txt'), 'r') 
lines = f.readlines() 
if len(lines) == 0: 
return 0 
line = lines[ - 1] 
dt = datetime.datetime.strptime(line, "%Y-%m-%d %H:%M:%S") 
lasttime = time.mktime(dt.utctimetuple()) 
f.close() 
return lasttime 
except: 
print('failed to get last modify time from txt file') 
return 0 
def registtime(): 
nowstr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) 
nowfloat = time.time() 
mypath = abspath(path[0]) # get current path 
f = open(join_path(mypath, 'C_UPGRADETIME.txt'), 'a') 
f.write('\n' + nowstr) 
f.close() 
def main(): 
c = config('config.xml') 
home = c.getSrcDir() 
dest = c.getDestDir() 
ignoreDirs = c.getNotIncludeDirs() 
ignoreFiles = c.getNotIncludeFiles() 
winRarDir = c.getWinRarDir() 
dest = getdestdir(dest)# get current dest directory 
print ('copy all files to the temp directory ignore last fetch time') 
fetchFiles(home, join_path(dest, 'temp'), ignoreDirs, ignoreFiles) 
print('tar the all files') 
tarfiles(join_path(dest, 'temp'), dest, winRarDir, 'CargillUpdate_ALL.rar') 
print('program sleep 20 seconds to finish the tar thread') 
time.sleep(20) 
print('remove the temp directory...') 
removeDir(join_path(dest, 'temp'), dest) 
print('success remove the temp directory') 
lasttime = getlasttime() # get last modify time from txt files 
if lasttime == 0: 
lasttime = c.getInitTime() 
print ('copy all files to the temp2 directory last modify time after last fetch time') 
fetchFiles(home, join_path(dest, 'temp2'), ignoreDirs, ignoreFiles, lasttime) 
print('tar the all files') 
tarfiles(join_path(dest, 'temp2'), dest, winRarDir, 'CargillUpdate.rar') 
print('program sleep 20 seconds to finish the tar thread') 
time.sleep(20) 
print('remove the temp2 directory...') 
removeDir(join_path(dest, 'temp2'), dest) 
print('success remove the temp2 directory') 
registtime() # regist current time 
if __name__ == '__main__': 
main()
Python 相关文章推荐
Python的ORM框架SQLObject入门实例
Apr 28 Python
Python中设置变量访问权限的方法
Apr 27 Python
python处理大数字的方法
May 27 Python
python学习 流程控制语句详解
Jun 01 Python
Python3 循环语句(for、while、break、range等)
Nov 20 Python
微信跳一跳python代码实现
Jan 05 Python
python中的随机函数小结
Jan 27 Python
python一行sql太长折成多行并且有多个参数的方法
Jul 19 Python
python单线程下实现多个socket并发过程详解
Jul 27 Python
python Matplotlib数据可视化(1):简单入门
Sep 30 Python
Django跨域请求原理及实现代码
Nov 14 Python
Python实现对齐打印 format函数的用法
Apr 28 Python
Python 文件重命名工具代码
Jul 26 #Python
python 生成目录树及显示文件大小的代码
Jul 23 #Python
python 域名分析工具实现代码
Jul 15 #Python
python 自动提交和抓取网页
Jul 13 #Python
python self,cls,decorator的理解
Jul 13 #Python
python 解析html之BeautifulSoup
Jul 07 #Python
打印出python 当前全局变量和入口参数的所有属性
Jul 01 #Python
You might like
要会喝咖啡也要会知道咖啡豆
2021/03/03 咖啡文化
Session保存到数据库的php类分享
2011/10/24 PHP
php上传文件,创建递归目录的实例代码
2013/10/18 PHP
PHP实现的同步推荐操作API接口案例分析
2016/11/30 PHP
PHP输出Excel PHPExcel的方法
2018/07/26 PHP
Avengerls vs KG BO3 第一场2.18
2021/03/10 DOTA
网页开发中的容易忽略的问题 javascript HTML中的table
2009/04/15 Javascript
js null,undefined,字符串小结
2010/08/21 Javascript
全面理解面向对象的 JavaScript(来自ibm)
2013/11/10 Javascript
js截取固定长度的中英文字符的简单实例
2013/11/22 Javascript
jQuery表格列宽可拖拽改变且兼容firfox
2014/09/03 Javascript
JQuery中Bind()事件用法分析
2015/05/05 Javascript
iView框架问题整理小结
2018/10/16 Javascript
JS实现深度优先搜索求解两点间最短路径
2019/01/17 Javascript
layUI实现前端分页和后端分页
2019/07/27 Javascript
js禁止查看源文件屏蔽Ctrl+u/s、F12、右键等兼容IE火狐chrome
2020/10/01 Javascript
使用vant的地域控件追加全部选项
2020/11/03 Javascript
[01:50]《我与DAC》之玩家:iG夺冠时的那面红旗
2018/03/29 DOTA
[32:17]完美世界DOTA2联赛循环赛LBZS vs Forest第二场 10月30日
2020/10/31 DOTA
python中关于时间和日期函数的常用计算总结(time和datatime)
2013/03/08 Python
整理Python最基本的操作字典的方法
2015/04/24 Python
使用Python实现BT种子和磁力链接的相互转换
2015/11/09 Python
Python中shutil模块的常用文件操作函数用法示例
2016/07/05 Python
对Python中DataFrame选择某列值为XX的行实例详解
2019/01/29 Python
Python3实现监控新型冠状病毒肺炎疫情的示例代码
2020/02/13 Python
pycharm通过anaconda安装pyqt5的教程
2020/03/24 Python
浅谈Python程序的错误:变量未定义
2020/06/02 Python
纯css3制作的火影忍者写轮眼开眼至轮回眼及进化过程实例
2014/11/11 HTML / CSS
详解CSS3 filter:drop-shadow滤镜与box-shadow区别与应用
2020/08/24 HTML / CSS
Urban Decay官方网站:美国化妆品品牌
2020/06/04 全球购物
JVM是一个编译程序还是解释程序
2012/09/11 面试题
大学生水文观测实习自我鉴定
2013/09/29 职场文书
数控个人求职信范文
2014/02/03 职场文书
自我推荐信范文
2014/05/09 职场文书
深入理解python协程
2021/06/15 Python
使用pipenv管理python虚拟环境的全过程
2021/09/25 Python