当前位置:首页 » 编程语言 » pythonforzip

pythonforzip

发布时间: 2025-01-16 11:59:46

㈠ 利用python编程,在多个打包压缩的文件中搜索指定字符串。有很多xml文件

ziprar.py

__author__='williezh'
#!/usr/bin/envpython3

importos
importsys
importtime
importshutil
importzipfile
fromzipfileimportZIP_DEFLATED


#Zip文件处理类
classZFile(object):
def__init__(self,fname,mode='r',basedir=''):
self.fname=fname
self.mode=mode
ifself.modein('w','a'):
self.zfile=zipfile.ZipFile(fname,mode,compression=ZIP_DEFLATED)
else:
self.zfile=zipfile.ZipFile(fname,self.mode)
self.basedir=basedir
ifnotself.basedir:
self.basedir=os.path.dirname(fname)

defaddfile(self,path,arcname=None):
path=path.replace('//','/')
ifnotarcname:
ifpath.startswith(self.basedir):
arcname=path[len(self.basedir):]
else:
arcname=''
self.zfile.write(path,arcname)

defaddfiles(self,paths):
forpathinpaths:
ifisinstance(path,tuple):
self.addfile(*path)
else:
self.addfile(path)

defclose(self):
self.zfile.close()

defextract_to(self,path):
forpinself.zfile.namelist():
self.extract(p,path)

defextract(self,fname,path):
ifnotfname.endswith('/'):
fn=os.path.join(path,fname)
ds=os.path.dirname(fn)
ifnotos.path.exists(ds):
os.makedirs(ds)
withopen(fn,'wb')asf:
f.write(self.zfile.read(fname))


#创建Zip文件
defcreateZip(zfile,files):
z=ZFile(zfile,'w')
z.addfiles(files)
z.close()


#解压缩Zip到指定文件夹
defextractZip(zfile,path):
z=ZFile(zfile)
z.extract_to(path)
z.close()


#解压缩rar到指定文件夹
defextractRar(zfile,path):
rar_command1="WinRAR.exex-ibck%s%s"%(zfile,path)
rar_command2=r'"C:WinRAR.exe"x-ibck%s%s'%(zfile,path)
try:
res=os.system(rar_command1)
ifres==0:
print("PathOK.")
except:
try:
res=os.system(rar_command2)
ifres==0:
print("Successtounrarthefile{}.".format(path))
except:
print('Error:cannotunrarthefile{}'.format(path))


#解压多个压缩文件到一个临时文件夹
defextract_files(file_list):
newdir=str(int(time.time()))
forfninfile_list:
subdir=os.path.join(newdir,fn)
ifnotos.path.exists(subdir):
os.makedirs(subdir)
iffn.endswith('.zip'):
extractZip(fn,subdir)
eliffn.endswith('.rar'):
extractRar(fn,subdir)
returnnewdir


#查找一个文件夹中的某些文件,返回文件内容包含findstr_list中所有字符串的文件
deffindstr_at(basedir,file_list,findstr_list):
files=[]
forr,ds,fsinos.walk(basedir):
forfninfs:
iffninfile_list:
withopen(os.path.join(r,fn))asf:
s=f.read()
ifall(iinsforiinfindstr_list):
files.append(os.path.join(r,fn))
returnfiles


if__name__=='__main__':
files=[iforiinsys.argv[1:]ifnoti.startswith('-')]
unzipfiles=[iforiinfilesifi.endswith('.zip')ori.endswith('.rar')]
xmlfiles=[iforiinfilesifi.endswith('.xml')]
save_unzipdir=Trueif'-s'insys.argvelseFalse
findstr=[i.split('=')[-1]foriinsys.argvifi.startswith('--find=')]
findstring=','.join(['`{}`'.format(i)foriinfindstr])
newdir=extract_files(unzipfiles)
result=findstr_at(newdir,xmlfiles,findstr)
ifnotresult:
msg='Noneofthefile(s)containthegivenstring{}.'
print(msg.format(findstring))
else:
msg='{}file(s)containthegivenstring{}:'
print(msg.format(len(result),findstring))
print(' '.join([i.replace(newdir+os.sep,'')foriinsorted(result)]))

ifnotsave_unzipdir:
shutil.rmtree(newdir)
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"--find="when"
Noneofthefile(s)containthegivenstring`Itwas`,`when`.
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"--find="I"
2file(s)containthegivenstring`Itwas`,`I`:
aaa.zip/aaa2.xml
aaa2.zip/aaa2.xml
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"
2file(s)containthegivenstring`Itwas`:
aaa.zip/aaa2.xml
aaa2.zip/aaa2.xml
热点内容
安卓怎么多开微信 发布:2025-03-09 08:34:02 浏览:593
怎么看金蝶服务器的ip地址 发布:2025-03-09 08:33:59 浏览:268
pyc在线反编译 发布:2025-03-09 08:33:17 浏览:932
天龙极速脚本 发布:2025-03-09 08:33:09 浏览:975
刀剑神域服务器维护到什么时候 发布:2025-03-09 08:31:40 浏览:216
phppdf转html 发布:2025-03-09 08:23:01 浏览:639
脚本按键怎么循环 发布:2025-03-09 08:19:06 浏览:142
intel的快速存储 发布:2025-03-09 08:18:25 浏览:609
ios天天酷跑刷积分脚本 发布:2025-03-09 08:12:01 浏览:736
2nf算法 发布:2025-03-09 08:05:15 浏览:931