python 提取文件的小程序

Jun 06, 2016 am 11:26 AM
python ファイルの抽出

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

代码如下:




    E:\temp\home\cargill
    E:\temp\dest\cargill
    
        
            

E:\temp\home\cargill\WEB-INF\lib
            E:\temp\home\cargill\static\cargill\report
        
        
            E:\temp\home\cargill\WEB-INF\classes\myrumba.xml
            E:\temp\home\cargill\META-INF\context.xml
        

    
    2008-10-11 13:15:22
    C:\Program Files\WinRAR


其中
:原始目录,即我们tomcat的发布目录;
:文件复制到得目标目录;
:需要忽略的文件夹和文件,具体需要忽略的内容在其子节点中定义,这里不在解释;
:这个是初始化需要提取的时间点,在这之后的才会提取,此处需要说明,后来在使用中,我增加了一个功能,就是每次提取完会自动将本次提取时间记录到一个文本文件C_UPGRADETIME.txt中,这就省去每次设置这个值的烦恼,只有C_UPGRADETIME.txt为空或者不存在时,才会用到这个值;
: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 element value of self.config_element
'''
srcDir = self.config_element.getElementsByTagName("srcdir")[0]
return self.getText(srcDir.childNodes)
def getDestDir(self):
'''
return the 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

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 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 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 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 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()

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

携帯電話でXMLをPDFに変換するとき、変換速度は高速ですか? 携帯電話でXMLをPDFに変換するとき、変換速度は高速ですか? Apr 02, 2025 pm 10:09 PM

Mobile XMLからPDFへの速度は、次の要因に依存します。XML構造の複雑さです。モバイルハードウェア構成変換方法(ライブラリ、アルゴリズム)コードの品質最適化方法(効率的なライブラリ、アルゴリズムの最適化、キャッシュデータ、およびマルチスレッドの利用)。全体として、絶対的な答えはなく、特定の状況に従って最適化する必要があります。

携帯電話のXMLファイルをPDFに変換する方法は? 携帯電話のXMLファイルをPDFに変換する方法は? Apr 02, 2025 pm 10:12 PM

単一のアプリケーションで携帯電話でXMLからPDF変換を直接完了することは不可能です。クラウドサービスを使用する必要があります。クラウドサービスは、2つのステップで達成できます。1。XMLをクラウド内のPDFに変換し、2。携帯電話の変換されたPDFファイルにアクセスまたはダウンロードします。

C言語合計の機能は何ですか? C言語合計の機能は何ですか? Apr 03, 2025 pm 02:21 PM

C言語に組み込みの合計機能はないため、自分で書く必要があります。合計は、配列を通過して要素を蓄積することで達成できます。ループバージョン:合計は、ループとアレイの長さを使用して計算されます。ポインターバージョン:ポインターを使用してアレイ要素を指し示し、効率的な合計が自己概要ポインターを通じて達成されます。アレイバージョンを動的に割り当てます:[アレイ]を動的に割り当ててメモリを自分で管理し、メモリの漏れを防ぐために割り当てられたメモリが解放されます。

XMLをPDFに変換できるモバイルアプリはありますか? XMLをPDFに変換できるモバイルアプリはありますか? Apr 02, 2025 pm 09:45 PM

XML構造が柔軟で多様であるため、すべてのXMLファイルをPDFSに変換できるアプリはありません。 XMLのPDFへのコアは、データ構造をページレイアウトに変換することです。これには、XMLの解析とPDFの生成が必要です。一般的な方法には、ElementTreeなどのPythonライブラリを使用してXMLを解析し、ReportLabライブラリを使用してPDFを生成することが含まれます。複雑なXMLの場合、XSLT変換構造を使用する必要がある場合があります。パフォーマンスを最適化するときは、マルチスレッドまたはマルチプロセスの使用を検討し、適切なライブラリを選択します。

XMLを写真に変換する方法 XMLを写真に変換する方法 Apr 03, 2025 am 07:39 AM

XMLは、XSLTコンバーターまたは画像ライブラリを使用して画像に変換できます。 XSLTコンバーター:XSLTプロセッサとスタイルシートを使用して、XMLを画像に変換します。画像ライブラリ:PILやImageMagickなどのライブラリを使用して、形状やテキストの描画などのXMLデータから画像を作成します。

推奨されるXMLフォーマットツール 推奨されるXMLフォーマットツール Apr 02, 2025 pm 09:03 PM

XMLフォーマットツールは、読みやすさと理解を向上させるために、ルールに従ってコードを入力できます。ツールを選択するときは、カスタマイズ機能、特別な状況の処理、パフォーマンス、使いやすさに注意してください。一般的に使用されるツールタイプには、オンラインツール、IDEプラグイン、コマンドラインツールが含まれます。

携帯電話でXMLを高品質でPDFに変換するにはどうすればよいですか? 携帯電話でXMLを高品質でPDFに変換するにはどうすればよいですか? Apr 02, 2025 pm 09:48 PM

携帯電話の高品質でXMLをPDFに変換する必要があります。クラウドでXMLを解析し、サーバーレスコンピューティングプラットフォームを使用してPDFを生成します。効率的なXMLパーサーとPDF生成ライブラリを選択します。エラーを正しく処理します。携帯電話の重いタスクを避けるために、クラウドコンピューティングの能力を最大限に活用してください。複雑なXML構造の処理、マルチページPDFの生成、画像の追加など、要件に応じて複雑さを調整します。デバッグを支援するログ情報を印刷します。パフォーマンスを最適化し、効率的なパーサーとPDFライブラリを選択し、非同期プログラミングまたは前処理XMLデータを使用する場合があります。優れたコードの品質と保守性を確保します。

Android電話でXMLをPDFに変換する方法は? Android電話でXMLをPDFに変換する方法は? Apr 02, 2025 pm 09:51 PM

Android電話でXMLをPDFに直接変換することは、組み込み機能を介して実現できません。次の手順を通じて国を保存する必要があります。XMLデータをPDFジェネレーター(テキストやHTMLなど)によって認識された形式に変換します。フライングソーサーなどのHTML生成ライブラリを使用して、HTMLをPDFに変換します。

See all articles