python batch decompression compressed file example code

  • 2021-07-03 00:32:19
  • OfStack

The following is an example code of python batch decompression compressed file, which is as follows;


#/usr/bin/python#coding=utf-8import os,sys 
import zipfile open_path='e:\\data'save_path='e:\\data' os.chdir(open_path)
# Go to the path 
# First, through zipfile Module opens at the specified location zip Documents 
# Pass in a list of file names, and the path where the list files are located, and the storage path def Decompression(files,file_path,save_path):  
os.getcwd()# Current path   os.chdir(file_path)# Go to the path   
for file_name in files:   
print(file_name)   
r = zipfile.is_zipfile(file_name)# Determine whether to extract the file    
if r:      
zpfd = zipfile.ZipFile(file_name)# Read compressed file      
os.chdir(save_path)# Go to storage path       
zpfd.extractall()      
zpfd.close()def files_save(open_path): 
for file_path,sub_dirs,files in os.walk(open_path):# Get all file names, paths    
print(file_path,sub_dirs,files)   
Decompression(files,file_path,save_path)files_save(open_path)

Look at the next 1 code python batch decompression


#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''Created on Jun 6, 2019
@author: carson
'''
import os
import re
import zipfile
import StringIO
#  The following 3 The line is to solve the coding problem 
import sys
reload(sys)
sys.setdefaultencoding('utf8')
file_path = r'/Users/qcq/Downloads/bills'
file_out = r'/Users/qcq/Downloads/qcq.txt'
#  Regular expressions match basic phone charges, information charges, long distance charges, 3 Entries. 
pattern = re.compile(r'\d+\.\d+')
phone_number_line = 1 # Mark the number of the document 1 The line is the phone number line 
real_bill_line = 7 #  Beginning of the text 
'''
1.  Code number 1 Section, first iterate the given file directory to get the zip File, stored in 1 List, for the following file processing services. This is mainly to use os.walk To iterate through the directory, and then use the os.path.join Connect two directories. 
'''
file_name_list = []
for dirpath, dirnames, filenames in os.walk(file_path):
  for file_name in filenames:
    if file_name.endswith('.zip'):
      temp_path = os.path.join(dirpath, file_name)
      file_name_list.append(temp_path)
'''
2.  The above files obtained are sorted to make the output order orderly. 
'''      
sorted(file_name_list)
'''
3.  Body part 
'''
with open(file_out, 'w') as f_out:
  for zip_file in file_name_list:
    with zipfile.ZipFile(zip_file) as f:
      data = {}
      for nameOfFileUnderZip in f.namelist():
        count = 1
        contents = StringIO.StringIO(f.read(nameOfFileUnderZip))
        sum_all = 0.0
        for line in contents:
          if count > phone_number_line and count < real_bill_line:
            count += 1
            continue
          if phone_number_line == count:
            phone_number = line.split(u' : ')[1]
            count += 1
            continue
          sum_all += sum(map(float, pattern.findall(line)))
        data[phone_number.strip()]=sum_all
      f_out.write(zip_file + '\n')
      for key, value in sorted(data.items(), key=lambda d:d[0]) :
        f_out.write(key + ':' + str(value) + '\n')

##############################################################################
#coding=utf-8
# Zhen Manong python Code 
# Use zipfile Do directory compression and decompression functions 
import os,os.path
import zipfile
def zip_dir(dirname,zipfilename):
  filelist = []
  if os.path.isfile(dirname):
    filelist.append(dirname)
  else :
    for root, dirs, files in os.walk(dirname):
      for name in files:
        filelist.append(os.path.join(root, name))
  zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
  for tar in filelist:
    arcname = tar[len(dirname):]
    #print arcname
    zf.write(tar,arcname)
  zf.close()
def unzip_file(zipfilename, unziptodir):
  if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
  zfobj = zipfile.ZipFile(zipfilename)
  for name in zfobj.namelist():
    name = name.replace('\\','/')
    if name.endswith('/'):
      os.mkdir(os.path.join(unziptodir, name))
    else:      
      ext_filename = os.path.join(unziptodir, name)
      ext_dir= os.path.dirname(ext_filename)
      if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
      outfile = open(ext_filename, 'wb')
      outfile.write(zfobj.read(name))
      outfile.close()
if __name__ == '__main__':
  zip_dir(r'E:/python/learning',r'E:/python/learning/zip.zip')
  unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')

Summarize

The above is the site to introduce the python batch decompression compressed file example code, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: