[Tutor] RE: how to zip data? (Branimir Petrovic)

Branimir Petrovic BranimirP at cpas.com
Tue Nov 23 15:44:16 CET 2004



> -----Original Message-----
> From: Eri Mendz [mailto:erimendz at gmail.com]
> 

> I'm trying to understanding this zip code. Can you kindly 
> explain what's happening step by step? 

Except this piece of loop (that runs as long as inputfile.read(chunksize)
has something to "pump out" from input file):

>             while chunkdata:
>                 gzoutfile.write(chunkdata)
>                 chunkdata = inputfile.read(chunksize)

everything else is easy to single step through and see for yourself 
what happens. Skip over loop by setting break points just before and 
after the loop, step manually through the rest, and you will understand 
how all works. 

I got used to Active State's Komodo for occasional debugging purposes,
but you may use whatever else (IDLE, ...)


> The try: finally clause is something new. 

try/finally is the way to ensure clean-up, no matter what. In case
of gzipIt/gunzipIt functions "finally" ensures that gzoutfile.close()
is called even if there were errors.
  
See "8.6 Defining Clean-up Actions":
http://docs.python.org/tut/node10.html#SECTION0010300000000000000000


> And also 
> what does the below code do? I see this always in the codes 
> in this group. I 
> seem not to encounter this (yet) in my tutorial reference. TIA
> 
> > if __name__=="__main__":

The above trick works like this: 

Every python script or imported module has __name__ property and
following rule holds:

	__name__ property of any script you may run is "__main__",

but
	__name__ property of imported module is imported module's name!

For instance, should I decide to import gzDemo as module from another
script:

# FileName: myOtherScript.py

import gzDemo	# gzDemo is compiled and executed, but since its
			# __name__ property at this point will be "gzDemo", 
			# if __name__ == "__main__":  will evaluate false
			# and the "demo case" (whatever was inside if) will
			# not be executed.

toZip = r'C:\stuff.txt'
gzDemo.gzipIt(toZip)

To summarize the trick "if __name__=="__main__":" is typically used
to add quick and dirty demo test case and/or to do actual work if
and only if the script is run as stand alone script.


Branimir 


More information about the Tutor mailing list