[Tutor] how to zip data?

Jacob S. keridee at jayco.net
Thu Nov 25 05:23:52 CET 2004


If y'all want just a zip file you can look at this...

### Zip.py ###

import zipfile, zlib, os
thething = 0
file = raw_input('What are you doing to the zip file? (Writing, Reading,
Unzipping) ')

#####################################################
##  Default values for directories are listed here ##
forschool = os.path.exists("F:\students\schmidja")
if not forschool:
    dirlist = os.listdir("c:\\")
    if 'Jacob Laptop' in dirlist:
        default = 'C:\\documents and settings\\jacob\\desktop'
    elif 'Home Computer' in dirlist:
        default = 'C:\\documents and settings\\owner\\desktop'
    elif 'Sissy Computer' in dirlist:
        default = 'C:\\windows\\desktop'
    elif 'Michael Laptop' in dirlist:
        default = 'C:\\documents and settings\\michael\\desktop'
    elif 'Office Computer' in dirlist:
        default = 'C:\\windows\\desktop'
    elif 'School Auction Laptop' in dirlist:
        default = 'C:\\windows\\desktop'
    else:
        print 'Hey you need to put a folder in this computer!. '
        print '''Folders include:
        Jacob Laptop
        Home Computer
        Sissy Computer
        Michael Laptop
        Office Computer
        School Auction Laptop
        '''
        folder = raw_input('Which computer is this? ')
        folder = os.path.join('C:',folder)
        os.mkdir(folder)
        default = input('Give me a default folder for this session. Please
update code for later use. ')
else:
    default = 'F:\students\schmidja'


##      Usually you want this as the desktop       ##
#####################################################
if file == "Writing":
    file = "a"
    usefile = "w"
elif file == "Reading":
    file = "r"
    usefile = "r"
elif file == "Unzipping":
    file = "r"
    usefile = "u"
else:
    print "That didn't work... Close the program and start over."

def printline(strng):
    t = 0
    for x in strng:
        if t < 20:
            print x
            t = t + 1
        else:
            raw_input()
            t = 0

def getsubs(dir):
    directorylist = []
    filelist = []
    for roots,directories,files in os.walk(dir):
        for x in files:
            directorylist.append(roots)
            filelist.append(x)
    return [directorylist,filelist]

def selectdir():
    ask2 = 'y'
    while ask2 == 'y':
        current = os.getcwd()
        c2 = current
        print "Current directory is: %s" % current
        ask = raw_input('Do you wish to see what\'s in current directory? ')
        if ask == 'y':
            printline(os.listdir(current))
        ask2 = raw_input('Do you wish to change directory? ')
        if ask2 == 'y':
            current = raw_input('What directory do you want? ')
            if current == '':
                current = default
            elif current.count('chdir') == 1:
                current = os.path.join(c2,current.lstrip('chdir '))
        os.chdir(current)

def fileselection():
    selectdir()
    name = raw_input('What is the file\'s name? ')
    while name == 'chdir':
        selectdir()
        name = raw_input('What is the file\'s name? ')
    return os.path.join(os.getcwd(),name)


os.chdir(default)
name = fileselection()
maindir,check = os.path.split(name)
new = os.listdir(maindir)
if check not in new:
    if file == 'a':
        file = 'w'
    else:
        print "You should never see this. It means that you are trying to
read a nonexistant zipfile. So there."
    print "Zip file %s was not there. I have hopefully created it for you. "
% (check)

zip = zipfile.ZipFile(name, file, zipfile.ZIP_DEFLATED)


if usefile == "w":
    all = raw_input('Do you wish to zip those with a particular extension?
')
    if all == 'y':
        selectdir()
        new = os.listdir(os.getcwd())
        while 1:
            ext = raw_input('Please type the extension. ')
            if ext == 'quit':
                break
            elif ext == 'all':
                include = raw_input("Should I include the subdirectories? ")
                m = os.getcwd()
                if include == 'y':
                    directorylist,filelist = getsubs(m)
                elif include == 'n':
                    filelist = [x for x in os.listdir(m) if
os.path.isfile(os.path.join(m,x))]
                    directorylist = [m for x in filelist]
                li = []
                for n in range(len(filelist)):
                    fpath = os.path.join(directorylist[n],filelist[n])
                    zip.write(fpath,filelist[n])
                    print "%s was copied to %s successfully. " %
(filelist[n],check)
                    li.append(fpath)
                d = raw_input('Would you like to delete these files? ')
                if d == 'y':
                    for x in li:
                        os.remove(x)
                        print "%s was removed successfully. " %
os.path.split(x)[1]
            elif ext == 'chdir':
                selectdir()
            else:
                delting = []
                ext = "."+ext
                for x in new:
                    extension = os.path.splitext(x)[1]
                    if extension == ext or extension == ext.upper() or
extension == ext.lower():
                        zip.write(x)
                        print "%s was copied to %s successfully. " %
(x,check)
                        delting.append(x)
                delete = raw_input("Do you wish to delete these files? ")
                if delete == 'y':
                    del x
                    for x in delting:
                        thing = os.path.join(os.getcwd(), x)
                        os.remove(thing)
                        print "%s was removed successfully. " % (x)
    if all == 'n':
        selectdir()
        listed = []
        while 1:
            thing=raw_input('What is the name of the file you want to add?
')
            if thing == 'all':
                include = raw_input("Should I include the subdirectories? ")
                m = os.getcwd()
                directorylist,filelist = getsubs(m)
                li = []
                for n in range(len(filelist)):
                    fpath = os.path.join(directorylist[n],filelist[n])
                    zip.write(fpath,filelist[n])
                    print "%s was copied to %s successfully. " %
(filelist[n],check)
                    li.append(fpath)
                d = raw_input('Do you wish to delete these files? ')
                if d == 'y':
                    for x in li:
                        os.remove(x)
                        tm = os.path.split(x)
                        print "%s was removed from %s successfully. " %
(tm[1],tm[0])
            elif thing == "quit":
                break
            elif thing == 'chdir':
                selectdir()
            else:
                try:
                    zip.write(thing)
                    listed.append(thing)
                except:
                    print "That file was not found. Please try another one."
        as = raw_input("Would you like to delete these files? ")
        if as == 'y':
            for x in listed:
                fpath2 = os.path.join(os.getcwd(),x)
                os.remove(fpath2)
                print "Removed %s successfully. " % (x)


if usefile == "r":
    while 1:
        forlatuse = os.getcwd()
        try:
            os.chdir('C:\\Python23\\Temp')
        except:
            os.mkdir('C:\\Python23\\Temp')
            os.chdir('C:\\Python23\\Temp')
        ask = raw_input('Do you wish to see what\'s in the zip file? ')
        if ask == 'quit':
            break
        elif ask == 'y':
            l = zip.namelist()
            printline(l)
        view0 = raw_input('What is the name of the file you want to open? ')
        if view0 == 'quit':
            break
        print view0
        filetoread = open(view0, 'wb')
        filetoread.write(zip.read(view0))
        filetoread.close()
        os.startfile(view0)
        null = raw_input('Press enter when done looking at file. ')
        os.remove(view0)
    os.chdir(forlatuse)


if usefile == "u":

    list = zip.namelist()
    hello = raw_input('Would you like to look at what is in the zip file? ')
    if hello == 'y':
        printline(list)
    dir = selectdir()
    dir = os.getcwd()

    ask = raw_input('Do you wish to unzip them all? ')
    if ask == 'y':
        thething = 1
        for item in list:
            huh = zip.read(item)
            thing = open(item, "wb")
            thing.write(huh)
            thing.close()
            print item, "was unzipped successfully."
    if ask == 'n':
        thething = 0
        while 1:
            item=raw_input('What is the name of the file you want to unzip?
')
            if item == "quit":
                break
            elif item == 'viewlist':
                printline(list)
            elif item in list:
                huh = zip.read(item)
                place = os.path.join(dir,item)
                thing = open(place, "wb")
                thing.write(huh)
                thing.close()
            else:
                print 'That file is not in the zip file. Type in "viewlist"
for a list of files in zip file. '
zip.close()
for x in locals().keys():
    try:
        x.close()
        print "Have been able to close %s" % x
    except:
        pass
if usefile == 'u':
    deleting = 'n'
    if thething == 1:
        deleting = raw_input('Would you like to delete the zip file %s that
you just unzipped? ' % check)
    if deleting == 'y':
        ask = raw_input('Are you sure you want to do this -- this will
delete the whole zip file!!! ')
        if ask == 'y':
            os.remove(name)
            print "Removed %s" % check

### End of Zip.py ###

>
> > -----Original Message-----
> > From: Ramkumar Parimal Alagan [mailto:ramster6 at gmail.com]
>
> > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> >
> > if os.system(zip_command) == 0:
> >     print 'Successful backup to', target
> > else:
> >     print 'Backup FAILED'
> >
>
>
> """No such a thing as "zip" command/utility on Windows, but using
> Python's standard library you could build your own....
>
> Example below shows how to gz-ip a file (if you wonder why .gz and
> not .zip: gzip library compresses as good and has no upper limit
> on how large file it can process).
>
> If below example looks too involving, you could purchase WinZip
> and get command line utility that will zip files for you via
> os.system call (but beware - WinZip can not zip/unzip files larger
> than 4 GB)
>
> Branimir
> """
>
> ######################################################################
> #   FileName    gzDemo.py
> ######################################################################
>
> import exceptions, os, re, gzip
>
> def gzipIt(filetogzip, gzippedname=None):
>     """Will GZIP file whose path is described by 'filetogzip' string.
>
>     Parameters:
>         filetogzip, gzippedname - STRING
>
>     By default (if 'gzippedname' not supplied):,
>         - will gunzip 'filetogzip' to same folder with the source file,
>         - will add '.gz' suffix to file name
>         - will remove source file after successful gzipping.
>
>     If 'gzippedname' is supplied, the source ('filetogzip') is not
removed.
>
>     Works like a charm although is 20% slower than GNU's gunzip utility.
>     """
>
>     chunksize=1048576
>     removesource = False
>
>     if not gzippedname:
>         gzippedname = filetogzip + r'.gz'
>         removesource = True
>
>     inputfile = file(filetogzip, r'rb', chunksize)
>     try:
>         chunkdata = inputfile.read(chunksize)
>         gzoutfile = gzip.open(gzippedname, mode='wb', compresslevel=5)
>         try:
>             while chunkdata:
>                 gzoutfile.write(chunkdata)
>                 chunkdata = inputfile.read(chunksize)
>         finally:
>             gzoutfile.close()
>     finally:
>         inputfile.close()
>
>     if removesource: os.remove(filetogzip)
>
>
> def gunzipIt(filetogunzip, gunzippedname=None):
>     """Will GUNZIP file whose path is described by 'filetogzip' string.
>
>     Parameters:
>         filetogunzip, gunzippedname - STRING
>
>     By default (if 'gunzippedname' not supplied):,
>         - will gunzip 'filetogunzip' to same folder with the source file,
>         - will strip '.gz' from file name suffix and
>         - will remove source file after successful gunzipping.
>
>     If 'gunzippedname' is supplied, the source ('filetogunzip') is not
> removed.
>
>     Works like a charm although is 30% slower than GNU's gunzip utility.
>     """
>
>     chunksize=8192
>     removesource = False
>
>     if not gunzippedname:
>         # strip '.gz' off the end of gzippedname
>         gunzippedname = re.sub('(\.(g|G)(z|Z))', '', filetogunzip)
>         removesource = True
>
>     fgunzip = gzip.open(filetogunzip, mode='rb')
>     try:
>         chunkdata = fgunzip.read(chunksize)
>         foutput = file(gunzippedname, r'wb', chunksize)
>         try:
>             while chunkdata:
>                 foutput.write(chunkdata)
>                 chunkdata = fgunzip.read(chunksize)
>         finally:
>             foutput.close()
>     finally:
>         fgunzip.close()
>
>     if removesource: os.remove(filetogunzip)
>
>
>
>
> if __name__=="__main__":
>
>     try:
>         # 1st run will "do-it:"
>         toZip = r'C:\_b\textStuff.txt'
>         gzipIt(toZip)
>     except exceptions.IOError:
>         # 2nd run will "un-do-it":
>         try:
>             toUnZip = r'C:\_b\textStuff.txt.gz'
>             gunzipIt(toUnZip)
>         except exceptions.IOError:
>              pass
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list