SoFunction
Updated on 2024-12-19

python removes files with specified suffixes from zip (recommended)

I. Description

Environment: python2
Modules used os zipfile shutil
Program Function: Remove files with specified suffixes from zip, then automatically compress them again

Function Description:

DelFileInZip(path,suffix)

path: the full path of the zip file
suffix: the specified file suffix.

II. Source code

import shutil
import zipfile
import os
from shutil import *
def UnZipFile(zip_src, dst_dir):# decompression function to decompress zip_src to dst_dir
  r = zipfile.is_zipfile(zip_src)
  if r:   
    fz = (zip_src, 'r')
    for file in ():
      (file, dst_dir)    
  else:
    print('This is not zip......')
def DelFileInZip(path,suffix):
  pathName=path[:('.')]
  pathName=()
  if not (pathName):
    (pathName,0o777)
  else:
    print pathName+' Already exist......'
  print("UnZip:"+path)
  UnZipFile(path,pathName)#Unpack the file to pathName,python3 can use shutil.unpack_archive(path, pathName, 'zip')
  for root,dirs,files in (pathName):# Traverse the pathName folder
    for f in files:
      fileName=(root,f)
      if((suffix)):#Find the file with the suffix suffix
        if (fileName):
          (fileName)# Delete the target file
          print('del:'+fileName)
        else:
          print fileName+" not file......"
  print('Zip:'+path)
  shutil.make_archive(pathName,'zip',pathName)# Compression
  (pathName)# Delete temporary files
  print('=======Finish!======')
  return ''
DelFileInZip('D:\\','log')

III. Results of implementation

summarize

The above is a small introduction to python from zip to remove the specified suffix file, I hope to help you, if you have any questions please leave me a message, I will reply to you in time. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!