1.过程:解压文件并复制文件到指定的位置 解压缩.gz的文件: 使用gzip 例程:
import os
import re
import gzip
import shutil
filePath = 'E:\\0.TLBOX文件整理\\17.千里眼测试\DS测试\9.18\home\\npsdk\log\\npsdk\\'
objPath = 'E:\\0.TLBOX文件整理\\17.千里眼测试\DS测试\9.18\\'
fileList = os.listdir(path=filePath)
gz_end = re.compile("gz$")
for file in fileList:
mo_file = gz_end.search(file)
if mo_file != None:
print(file)
print(filePath+file)
f_name = file.replace(".gz", "")
g_file = gzip.GzipFile(filePath+file)
open(f_name,"wb+").write(g_file.read())
shutil.copyfile(f_name,objPath+f_name)
g_file.close()
os.remove(f_name)
使用到的内容: re:正则表达式,匹配待处理的文件名字 os:进行文件删除等操作 shutil:复制文件到指定位置 gzip:解压和压缩文件 2. 程序主体:
import os
import shutil
import gzip
import re
import time
npPath = 'E:\\0.TLBOX文件整理\\17.千里眼测试\DS测试\9.18\home\\npsdk\log\\npsdk\\'
spPath = 'E:\\0.TLBOX文件整理\\17.千里眼测试\DS测试\9.18\home\\npsdk\log\\south\\'
filePath = 'E:\\0.TLBOX文件整理\\17.千里眼测试\DS测试\9.18\\'
northLog = 'log'
proTcpLog = 'ProtocolModbusTcp'
proLog = 'ProtocolModbus'
dataprocLog = 'DataProc'
southLog = 'DeraSP'
offlineKey = ['device offline','create offline','devstatus']
gz_end = re.compile('gz$')
logList = []
def gzipFile(gzPath,filePath):
gzList = os.listdir(path=gzPath)
for file in gzList:
labelFile = gz_end.search(file)
if labelFile != None:
f_name = file.replace(".gz","")
g_file = gzip.GzipFile(gzPath+file)
open(f_name,"wb+").write(g_file.read())
time.sleep(0.1)
shutil.copyfile(f_name,filePath+f_name)
g_file.close()
os.remove(f_name)
def fileExtract(fileList,keyWord):
print("extract")
for file in fileList:
with open(filePath+file,'r') as f:
while True:
m = f.readline()
xList = []
for Word in keyWord:
x = m.rfind(Word)
xList.append(x)
for x in xList:
if x != -1:
logList.append(m)
break
if m == '':
break
def timeExtract(fileList,timePeriod):
for file in fileList:
with open(file,'r') as f:
while True:
m = f.readline()
if m[0:23] >= timePeriod[0] and m[0:23] <= timePeriod[1]:
logList.append(m)
if m == '':
break
def fileListExtract(path,keyWordF,keyWordL):
kList = []
re_key = re.compile("^"+keyWordF)
fList = os.listdir(path)
for file in fList:
labelF = re_key.search(file)
if labelF != None:
kList.append(file)
print(kList)
fileExtract(kList, keyWordL)
def fileWrite(terFile):
with open(terFile, 'w') as f2:
for offline in logList:
f2.writelines(offline)
def main():
npFile = 'npoffline.txt'
spFile = 'spoffline.txt'
gzipFile(spPath,filePath)
fileListExtract(filePath,dataprocLog,offlineKey)
fileWrite(spFile)
gzipFile(npPath, filePath)
fileListExtract(filePath, northLog, offlineKey)
fileWrite(npFile)
if __name__ == '__main__':
main()
|