Python unzip zip and rar files to the specified directory

Source: Internet
Author: User
Tags rar

#__author__ = ' Joker '
#-*-Coding:utf-8-*-
Import Urllib
Import OS
Import Os.path
Import ZipFile
From ZipFile Import *
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' GBK ')

RootDir = "F:/50_gis/1000_tools" # indicates the folder being traversed
Zipdir = "F:/000_terrain/zipdir" # Stores unpacked folders

#Zip文件处理类
Class Zfile (object):
def __init__ (self, filename, mode= ' R ', basedir= "):
Self.filename = filename
Self.mode = mode
If Self.mode in (' W ', ' A '):
Self.zfile = ZipFile. ZipFile (filename, Self.mode, compression=zipfile. zip_deflated)
Else
Self.zfile = ZipFile. ZipFile (filename, Self.mode)
Self.basedir = Basedir
If not self.basedir:
Self.basedir = os.path.dirname (filename)

def addfile (self, Path, Arcname=none):
Path = Path.replace ('//', '/')
If not arcname:
If Path.startswith (self.basedir):
Arcname = Path[len (self.basedir):]
Else
Arcname = ' '
Self.zfile.write (Path, arcname)

def addfiles (self, Paths):
For path in paths:
If isinstance (path, tuple):
Self.addfile (*path)
Else
Self.addfile (PATH)

def close (self):
Self.zfile.close ()

def extract_to (self, Path):
For P in Self.zfile.namelist ():
Self.extract (p, path)

Def extract (self, filename, path):
If not filename.endswith ('/'):
f = os.path.join (path, filename)
dir = Os.path.dirname (f)
If not os.path.exists (dir):
Os.makedirs (dir)
File (f, ' WB '). Write (Self.zfile.read (filename))

#创建Zip文件
def createzip (zfile, files):
z = zfile (zfile, ' W ')
Z.addfiles (Files)
Z.close ()

#解压缩Zip到指定文件夹
def extractzip (Zfile, path):
z = zfile (zfile)
Z.extract_to (PATH)
Z.close ()

#解压缩rar到指定文件夹
def extractrar (Zfile, path):
Rar_command1 = "WinRAR.exe x-ibck%s%s"% (zfile, path)
Rar_command2 = R ' "C:\WinRAR.exe" x-ibck%s%s '% (zfile, path)
If Os.system (rar_command1) = = 0:
print "Path OK."
Else

If Os.system (rar_command2)! = 0:
Print "Error."
Else
print "Exe OK"

#获得文件名和后缀
def getfilenameandext (filename):
(filepath,tempfilename) = os.path.split (filename);
(shotname,extension) = Os.path.splitext (TempFileName);
Return shotname,extension

#定义文件处理数量-Global variables
FileCount = 0

#递归获得rar文件集合
def getFiles (filepath):
#遍历filepath下所有文件, including sub-directories
Files = Os.listdir (filepath)
For fi in Files:
Fi_d = Os.path.join (FILEPATH,FI)
If Os.path.isdir (fi_d):
GetFiles (Fi_d)
Else
Global FileCount
Global Zipdir
FileCount = FileCount + 1
# Print FileCount
FileName = Os.path.join (filepath,fi_d)
Filenamenoext = Getfilenameandext (FileName) [0]
Fileext = Getfilenameandext (FileName) [1]
# If you want to save to the same folder, set the file name to empty
Filenamenoext = ""
Zipdirdest = Zipdir + "/" + Filenamenoext + "/"
If fileext in ['. zip ', '. rar ']:
If not Os.path.isdir (zipdirdest):
Os.mkdir (Zipdirdest)
if Fileext = = ". Zip": #
Print str (filecount) + "--" + fileName
# Unzip (filename,zipdirdest)
Extractzip (Filename,zipdirdest)
elif Fileext = = ". rar":
Print str (filecount) + "--" + fileName
Extractrar (FileName, Zipdirdest)

List of files #递归遍历 the specified suffix in the "RootDir" directory
GetFiles (RootDir)

File Processing reference: http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html

Python unzip zip and rar files to the specified directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.