Python 压缩文件解压文件

 

f=zipfile.ZipFile("test.zip",mode="")  //mode 解压是 r , 压缩是 w, 追加压缩是 a

 

 

压缩文件

import zipfile
def zip_files( files, zip_name ):
    zip = zipfile.ZipFile( zip_name, 'w', zipfile.ZIP_DEFLATED )
    for file in files:
        print ('compressing', file)
        zip.write( file )
    zip.close()
    print ('compressing finished')


files = ['D:\\temp-test\\abc.txt', 'D:\\temp-test\\bbb.txt'] #多个文件的路径和名称,多个文件用“,”隔开
zip_file = 'D:\\temp-test\\ccc.txt.zip' #压缩之后的包名字
zip_files(files, zip_file)

 压缩一个文件

import zipfile
try:
  with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="w") as f:
    f.write("c://users//17250//desktop//test.txt")          #写入压缩文件,会把压缩文件中的原有覆盖
except Exception as e:
    print("异常对象的类型是:%s"%type(e))
    print("异常对象的内容是:%s"%e)
finally:
    f.close()

 

追加一个文件

import zipfile #向已存在的压缩文件中追加内容
try:
  with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="a") as f:
    f.write("e://test.txt")          #追加写入压缩文件
except Exception as e:
    print("异常对象的类型是:%s"%type(e))
    print("异常对象的内容是:%s"%e)
finally:
    f.close()

 

import zipfile, os

def zip_files(files, zip_name):
    zip = zipfile.ZipFile( zip_name, 'w', zipfile.ZIP_DEFLATED )
    for file in files:
        print ('compressing', file)
        zip.write( file )
        res = zip.testzip()
        if res:
           print(res)
           #raise Exception('Zip file from \'{0!s}\' was corrupt.'.format(file))
    zip.close()
    print ('compressing finished')


files = ['D:\\temp-test\\abc.txt', 'D:\\temp-test\\bbb.txt'] #文件的位置,多个文件用“,”隔开
zip_file = 'D:\\temp-test\\ccc.txt.zip' #压缩包名字
#os.remove(zip_file)
zip_files(files, zip_file)

 

 

检查压缩文件

 

 

解压文件

 

import zipfile

zip_file = zipfile.ZipFile('D:\\temp-test\\ccc.txt.zip')
# 解压
zip_extract = zip_file.extractall() ## 解压到当前目录(运行python程序的目录)
zip_file.close()

 

import zipfile

zip_file = zipfile.ZipFile('D:\\temp-test\\ccc.txt.zip')
# 解压
for names in zip_file.namelist():
    zip_file.extract(names, 'D:\\temp-test\\' )

zip_file.close()

 

import zipfile
try:
  with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="a") as f:
     f.extractall("c://users//17250//desktop//",pwd=b"root") ##将文件解压到指定目录,解压密码为root
except Exception as e:
     print("异常对象的类型是:%s"%type(e))
     print("异常对象的内容是:%s"%e)
finally:
     f.close()

 

 

 

REF

https://www.cnblogs.com/chenlove/p/9526707.html

https://www.jb51.net/article/188637.htm

https://vimsky.com/examples/detail/python-ex-zipfile-ZipFile-testzip-method.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章