python 提取文件的小程序_python

以前提取这些文件用的是一同事些的批处理文件;用起来不怎么顺手,刚好最近在学些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()

时间: 2024-09-13 14:11:23

python 提取文件的小程序_python的相关文章

python读写文件操作示例程序_python

文件操作示例 复制代码 代码如下: #输入文件f = open(r'D:\Python27\pro\123.bak') #输出文件fw = open(r'D:\Python27\pro\123e.bak','w')#按行读出所有文本lines = f.readlines()num = -1for line in lines:    str = '@SES/%i/' %num    line = line.replace('@SES/1/',str)    num = num + 1    #写入

刚学的java,写了个压缩文件的小程序,一直没有成功

问题描述 刚学的java,写了个压缩文件的小程序,一直没有成功 public class f2Test { public static void main(String[] args){ frame02 f2=new frame02(); } } import java.awt.BorderLayout; import java.awt.Color; import java.awt.Image; import java.awt.Menu; import java.awt.MenuBar; imp

Python实现的检测web服务器健康状况的小程序_python

对web服务器做健康检查,一般我们都是用curl库(不管是php,perl的还是shell的),大致的方法一致: 复制代码 代码如下: curl -I -s www.qq.com  |head -1|awk '{ health = $2=="200"?"server is ok":"server is bad"}END{print health}' server is ok 说白了这些方式都是封装了curl库的,另外还有一些关于http的模块,例

一个计算身份证号码校验位的Python小程序_python

S = Sum(Ai * Wi), i=0,.......16 (现在的身份证号码都是18位长,其中最后一位是校验位,15位的身份证号码好像不用了) Ai对应身份证号码,Wi则为用于加权计算的值,它一串固定的数值,应该是根据某种规则得出的吧,用于取得最好的随机性,Wi的取之如下: 7   9 10 5 8   4   2   1 6   3   7   9 10  5   8   4   2 经过加权计算之后,得到一个S,用这个S去模11,取余值,然后查表得到校验位,这个索引表如下: 0 ---

用Python编写一个国际象棋AI程序_python

最近我用Python做了一个国际象棋程序并把代码发布在Github上了.这个代码不到1000行,大概20%用来实现AI.在这篇文章中我会介绍这个AI如何工作,每一个部分做什么,它为什么能那样工作起来.你可以直接通读本文,或者去下载代码,边读边看代码.虽然去看看其他文件中有什么AI依赖的类也可能有帮助,但是AI部分全都在AI.py文件中. AI 部分总述 AI在做出决策前经过三个不同的步骤.首先,他找到所有规则允许的棋步(通常在开局时会有20-30种,随后会降低到几种).其次,它生成一个棋步树用来

python提取内容关键词的方法_python

本文实例讲述了python提取内容关键词的方法.分享给大家供大家参考.具体分析如下: 一个非常高效的提取内容关键词的python代码,这段代码只能用于英文文章内容,中文因为要分词,这段代码就无能为力了,不过要加上分词功能,效果和英文是一样的. 复制代码 代码如下: # coding=UTF-8 import nltk from nltk.corpus import brown # This is a fast and simple noun phrase extractor (based on

Python open()文件处理使用介绍_python

1. open()语法 open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]]) open函数有很多的参数,常用的是file,mode和encodingfile文件位置,需要加引号mode文件打开模式,见下面3buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小:enco

python读写文件操作示例程序

 日常操作中,少不了文本处理,如程序输入数据准备,python凭借其简洁优雅的语法,在文本处理上比C++等编译型语言开发效率高出一大截,下面看代码 文件操作示例     复制代码 代码如下: #输入文件 f = open(r'D:Python27pro123.bak')  #输出文件 fw = open(r'D:Python27pro123e.bak','w') #按行读出所有文本 lines = f.readlines() num = -1 for line in lines:     str

跟老齐学Python之做一个小游戏_python

在讲述有关list的时候,提到做游戏的事情,后来这个事情一直没有接续.不是忘记了,是在想在哪个阶段做最合适.经过一段时间学习,看官已经不是纯粹小白了,已经属于python初级者了.现在就是开始做那个游戏的时候了. 游戏内容:猜数字游戏 太简单了吧.是的,游戏难度不大,不过这个游戏中蕴含的东西可是值得玩味的. 游戏过程描述 程序运行起来,随机在某个范围内选择一个整数. 提示用户输入数字,也就是猜程序随即选的那个数字. 程序将用户输入的数字与自己选定的对比,一样则用户完成游戏,否则继续猜. 使用次数