skip to main | skip to sidebar

Python Programs and Examples

Pages

  • Home
 
  • RSS
  • Facebook
  • Twitter
Tuesday, October 23, 2012

Python script to zip and unzip files

Posted by Raju Gupta at 9:30 PM – 5 comments
 

# Simple Application/Script to Compress a File or Directory
# Essentially you could use this instead of Winzip

"""
Path can be a file or directory
Archname is the name of the to be created archive
"""
from zipfile import ZipFile, ZIP_DEFLATED
import os  # File stuff
import sys # Command line parsing
def zippy(path, archive):
    paths = os.listdir(path)
    for p in paths:
        p = os.path.join(path, p) # Make the path relative
        if os.path.isdir(p): # Recursive case
            zippy(p, archive)
        else:
            archive.write(p) # Write the file to the zipfile
    return

def zipit(path, archname):
    # Create a ZipFile Object primed to write
    archive = ZipFile(archname, "w", ZIP_DEFLATED) # "a" to append, "r" to read
    # Recurse or not, depending on what path is
    if os.path.isdir(path):
        zippy(path, archive)
    else:
        archive.write(path)
    archive.close()
    return "Compression of \""+path+"\" was successful!"

instructions = "zipit.py:  Simple zipfile creation script." + \
               "recursively zips files in a directory into" + \
               "a single archive." +\
               "e.g.:  python zipit.py myfiles myfiles.zip"

# Notice the __name__=="__main__"
# this is used to control what Python does when it is called from the
# command line.  I'm sure you've seen this in some of my other examples.
if __name__=="__main__":
    if len(sys.argv) >= 3:
        result = zipit(sys.argv[1], sys.argv[2])
        print result
    else:
        print instructions


================================================================================


# Simple script to Unzip archives created by
# our Zip Scripts.

import sys
import os
from zipfile import ZipFile, ZIP_DEFLATED

def unzip( path ):
    # Create a ZipFile Object Instance
    archive = ZipFile(path, "r", ZIP_DEFLATED)
    names = archive.namelist()
    for name in names:
        if not os.path.exists(os.path.dirname(name)):
            # Create that directory
            os.mkdir(os.path.dirname(name))
        # Write files to disk
        temp = open(name, "wb") # create the file
        data = archive.read(name) #read the binary data
        temp.write(data)
        temp.close()
    archive.close()
    return "\""+path+"\" was unzipped successfully."
    
instructions = "This script unzips plain jane zipfiles:"+\
               "e.g.:  python unzipit.py myfiles.zip"

if __name__=="__main__":
    if len(sys.argv) == 2:
        msg = unzip(sys.argv[1])
        print msg
    else:
        print instructions


Labels: Zip File Example Email This BlogThis! Share to X Share to Facebook

5 Responses so far.

  1. Arthur says:
    November 17, 2017 at 5:28 AM

    As for unpacking, the script is
    quite complicated and not so justified in use, but if I know how to open zip file https://wikiext.com/zip this means that the most popular problems are already listed in the list, and solutions have been found for them. I advise you to use this, and I myself came to such a list, thanks to the advice of my project manager.

  2. navya says:
    December 15, 2018 at 5:39 AM

    Great Article
    B.Tech Final Year Projects for CSE in Python
    FInal Year Project Centers in Chennai


    JavaScript Training in Chennai
    JavaScript Training in

    Chennai

  3. subhashini says:
    September 3, 2019 at 5:43 AM


    Admire this blog. Keep sharing more updates like this
    Data Science Training in Chennai
    Data Science Course in Chennai
    Data Science Courses in Bangalore
    Data science course in coimbatore
    Data Science Certification in Chennai
    Data Science Classes in Chennai
    Data Science Training Institute in Chennai
    Software Testing Training in Chennai

  4. AK Blogger says:
    April 5, 2020 at 7:14 PM

    I often use online converters to convert files (e.g. doc to pdf, tiff to jpg, etc.). The best in my ranking - https://anyconv.com/ anyconv.com

  5. Huongkv says:
    March 25, 2021 at 3:18 AM

    Aivivu đại lý vé máy bay, tham khảo

    kinh nghiệm mua vé máy bay đi Mỹ giá rẻ

    vé máy bay hàn quốc hà nội

    mua vé máy bay pleiku đi sài gòn

    vé máy bay đi hà nội giá bao nhiêu

    vé máy bay từ texas về việt nam

    taxi sân bay nội bài

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments (Atom)
  • Popular
  • Recent
  • Archives

Popular Posts

  • To Send the entire contents of directory as an email Message.
    Here is a Python Program to send the entire contents of a directory as an email message #!/usr/bin/env python """Send the...
  • Control Structures in Python
    This Program explains different control structures in python If ==== # basic "If" if boolean: x = 1 else: x = 0 # No...
  • Python Code for creating Screen saver
    This is the Python code for creating a screensaver of a moving ball. The ball will bee moving along the screen and when it hits any of the ...
  • Python script for walking the directory tree structure but excluding some directories and files
    The script walks the directory structure recursively. Some of the directories and files can be excluded from the walk by providing them in ...
  • XML to CSV Converter
    Python Program to extract each execution data (few children in xml) and create a csv file. def xml2csv(inputFile,outputFile,elemName,n...
  • HTML Email using Python
    We created a module called sendmail which email html content. Each of application dumps data from the datastructure into html format and th...
  • Overview of Python Programming Language
    Python is an easy to learn, powerful programming language. It has efficient high level data structures and a simple but effective approac...
  • Fast and efficient Backup script that works on Windows and Linux
    This python script backup your directory structure that works on Linux and Windows both. It directly uses the shell to do this task and she...
  • Run Application from host
    import os os.execl( "c:/Windows/Notepad.exe", "c:/userlog.txt") print "Running notepad" #or import subpro...
  • Orphan Checker
    The script does not use any outside libraries, thus keeping its execution simple. we will start by initializing the arrays that we'll...
Powered by Blogger.

Archives

  • ▼  2012 (66)
    • ▼  October (28)
      • Find text/pattern under parent folder from matched...
      • XML to CSV Converter
      • XSL to CSV converter
      • Spell Corrector in Python
      • Format a plain ASCII file using Python script
      • Control Structures in Python
      • Python script to zip and unzip files
      • Fast and efficient Backup script that works on Win...
      • File Splitter Script
      • Python script for walking the directory tree struc...
      • Python XML Parser
      • IP Address Generation
      • Orphan Checker
      • HTML Email using Python
      • Python interface to load commands.
      • Python script to Validate Tabular format Data and ...
      • Python script to Load Configuration file content i...
      • Python Script to search file for specific content
      • Network Wise File Concatenation
      • Python Script for Adding or Subtracting the Dates
      • Program to create make file in VMS/UNIX
      • Python Code for creating Screen saver
      • Run Application from host
      • Multithreading in Python
      • This utility determines the size of a folder and i...
      • Using UNIX Environment Variables From Python
      • CVS Macro for Commited Files
      • Generating unique id's
    • ►  September (36)
    • ►  March (1)
    • ►  February (1)
 

Labels

  • Command Execution Using Python (2)
  • Control Structure (1)
  • CSV Examples (4)
  • Database (3)
  • Features of Python Programming Language (1)
  • File Example (2)
  • IF Statement (1)
  • List (2)
  • Mail (5)
  • Multithreading (1)
  • MySQL (3)
  • Python Date Example (2)
  • Python Example (2)
  • Python File Example (7)
  • Python Introduction (1)
  • Python Network Example (1)
  • Python XML Parser (2)
  • Searching Example (2)
  • Simple Calculation Program (1)
  • Strings (4)
  • Zip File Example (1)

Followers

 
 
© 2011 Python Programs and Examples | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger