Python UnZipped - Listings in the Key of Zip (Page 3 of 3 )
Finally were going to look at a function that uses recursion to move though a Zip file and its sub archives; returning a complete list of all none Zip files. But what’s the point in this? Let's say for instance that you want to count the number of files in a Zip, this way all you have to do is call len() on our function. Enough talk lets see this function in action.
<br />#!/usr/bin/env python</p>
<p> </p>
<p>import os, zipfile</p>
<p> </p>
<p>def rezipe(path, files = []):</p>
<p> </p>
<p>zip = zipfile.ZipFile(path)</p>
<p> </p>
<p>for name in zip.namelist():</p>
<p>if name.endswith('.zip'):</p>
<p>file(name, 'wb').write(zip.read(name))</p>
<p>rezipe(name)</p>
<p>os.remove(name)</p>
<p>elif not name.endswith('/'):</p>
<p>files.append(name)</p>
<p> </p>
<p>return files</p>
<p> </p>
<p>print len(rezipe('Python.zip'))
<br />
But wait, there's... uhm... nevermind. That's it. Sorry if I hyped that last one up a bit.
Unlike our other examples rezipe() opens the Zip file itself instead of using one we’ve already opened. It then loops though zip.namelist() and if name ends with .zip we extract it to the current working directory and call rezipe() on it, removing it when rezipe() is complete. The next part simply says if name isn’t a Zip file or a folder append it to the end of our list.
If your anything like me by now I’m sure you can see the potential this little guy (in particular) has and what this means for your Zip files!
If you’ve found this article interesting and you want to learn more about Python or some of the subjects covered here:
http://www.python.org/ - Python homepage
http://www.python.org/doc/2.3.2/tut/tut.html - Python tutorial
http://www.python.org/doc/2.3.2/modindex.html - Python module index
http://www.python.org/doc/2.3.2/lib/module-zipfile.html - The zipfile module
Note: All the examples shown and discussed in this article where tested on Windows XP with Python 2.3 and are meant only as examples.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |