pipihaoke

【Python压缩文件夹】导入“zipfile”模块

 1 def zip_ya(startdir,file_news):
 2     startdir = ".\\123"  #要压缩的文件夹路径
 3     file_news = startdir +\'.zip\' # 压缩后文件夹的名字
 4     z = zipfile.ZipFile(file_news,\'w\',zipfile.ZIP_DEFLATED) #参数一:文件夹名
 5     for dirpath, dirnames, filenames in os.walk(startdir):
 6         fpath = dirpath.replace(startdir,\'\') #这一句很重要,不replace的话,就从根目录开始复制
 7         fpath = fpath and fpath + os.sep or \'\'#这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩
 8         for filename in filenames:
 9             z.write(os.path.join(dirpath, filename),fpath+filename)
10             print (\'压缩成功\')
11     z.close()
12 
13 if__name__=="__main__"
14     startdir = ".\\123"  #要压缩的文件夹路径
15     file_news = startdir +\'.zip\' # 压缩后文件夹的名字 
16     zip_ya(startdir,file_news)

【python压缩文件】导入“zipfile”模块

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 = [\'.\\123.txt\',\'.\\3.txt\']#文件的位置,多个文件用“,”隔开
zip_file = \'.\\m66y.zip\'#压缩包名字
zip_files(files, zip_file)

 

分类:

技术点:

相关文章:

  • 2022-01-08
  • 2022-01-27
  • 2021-06-02
  • 2021-10-18
  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2021-09-16
猜你喜欢
  • 2022-01-06
  • 2022-01-13
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
  • 2022-12-23
相关资源
相似解决方案