I'm relatively new to python, and am trying to zip a directory containing several levels of files and folders. I can use the walk function to name each file in my directory, and I can use zipfile to zip a flat number of files in one folder, but I am having heck of a time trying to zip the whole directory. I want to zip it all to a file called "help.zip", and I want it to retain the original file structure.
Of my several tries, here is the latest: -
import zipfile, os
-
-
def main():
-
zip = "help3.zip"
-
directory = "//groupstore/workgroups/documentation/test"
-
toZip(directory)
-
-
-
def toZip(directory):
-
zippedHelp = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
-
-
list = os.listdir(directory)
-
-
for entity in list:
-
each = os.path.join(directory,entity)
-
-
if os.path.isfile(each):
-
print each
-
zippedHelp.write(each,zipfile.ZIP_DEFLATED)
-
else:
-
addFolderToZip(zippedHelp,entity)
-
-
zippedHelp.close()
-
-
#def addFolderToZip(zippedHelp,folder):
-
-
for file in folder:
-
if os.path.isfile(file):
-
zippedHelp.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
-
elif os.path.isdir(file):
-
addFolderToZip(zippedHelp,file)
-
main()
-
10 38566 bvdet 2,851
Recognized Expert Moderator Specialist
Here's a script that I use to backup the contents of a directory and it's subdirectories. It can easily be adjusted to backup only the directory contents or files with specific extensions. The file path is saved in the archive. - import zipfile, os
-
-
def makeArchive(fileList, archive):
-
"""
-
'fileList' is a list of file names - full path each name
-
'archive' is the file name for the archive with a full path
-
"""
-
try:
-
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
-
for f in fileList:
-
print "archiving file %s" % (f)
-
a.write(f)
-
a.close()
-
return True
-
except: return False
-
-
def dirEntries(dir_name, subdir, *args):
-
'''Return a list of file names found in directory 'dir_name'
-
If 'subdir' is True, recursively access subdirectories under 'dir_name'.
-
Additional arguments, if any, are file extensions to match filenames. Matched
-
file names are added to the list.
-
If there are no additional arguments, all files found in the directory are
-
added to the list.
-
Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py')
-
Only files with 'txt' and 'py' extensions will be added to the list.
-
Example usage: fileList = dirEntries(r'H:\TEMP', True)
-
All files and all the files in subdirectories under H:\TEMP will be added
-
to the list.
-
'''
-
fileList = []
-
for file in os.listdir(dir_name):
-
dirfile = os.path.join(dir_name, file)
-
if os.path.isfile(dirfile):
-
if not args:
-
fileList.append(dirfile)
-
else:
-
if os.path.splitext(dirfile)[1][1:] in args:
-
fileList.append(dirfile)
-
# recursively access file names in subdirectories
-
elif os.path.isdir(dirfile) and subdir:
-
print "Accessing directory:", dirfile
-
fileList.extend(dirEntries(dirfile, subdir, *args))
-
return fileList
-
-
if __name__ == '__main__':
-
folder = r'D:\Zip_Files\611 Lenox'
-
zipname = r'D:\Zip_Files\611 Lenox\test.zip'
-
makeArchive(dirEntries(folder, True), zipname)
-
HTH
Here's a script that I use to backup the contents of a directory and it's subdirectories. It can easily be adjusted to backup only the directory contents or files with specific extensions. The file path is saved in the archive.
Thank you!! Yay. I used your script to make mine work and I'm getting a better understanding of recursive functions. That was definitely where my hangup had been. Thanks again!!
@bvdet
Thanks, this is just what i was looking for in my pys60 app :D. Thanks again for the help :)
you can also do this, which is MUCH more concise: - def recursive_zip(zipf, directory, folder=None):
-
list = os.listdir(directory)
-
-
for file in list:
-
if os.path.isfile(file):
-
zipf.write(file, folder, zipfile.ZIP_DEFLATED)
-
elif os.path.isdir(file):
-
recursive_zip(zipf, os.path.join(directory, file), file)
bvdet 2,851
Recognized Expert Moderator Specialist
Nakubu,
Thank you for your contribution. Please use code tags when posting code in the future.
It's not a good idea to use list and file as names of variables. The built-in functions list() and file() will be masked until the objects are deleted.
I have a question. Is zipf an open file object? It would be helpful to others reading this thread if you would post sample code that creates the file object, calls recursive_zip(), and closes the file object.
BV - Moderator
here's a revised version: -
def recursive_zip(zipf, directory, folder=None):
-
nodes = os.listdir(directory)
-
-
for item in nodes:
-
if os.path.isfile(item):
-
zipf.write(item, folder, zipfile.ZIP_DEFLATED)
-
elif os.path.isdir(item):
-
recursive_zip(zipf, os.path.join(directory, item), item)
-
-
zipf is an opened zipfile.ZipFile instance. For example: -
zipf = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
-
path = '/Users/nakubu/some_folder'
-
recursive_zip(zipf, path) //leave the first folder as None, as path is root.
-
zipf.close()
-
I found Nakubu's function helpful, but needed to modify it in several ways. Hope this helps someone: -
def recursive_zip(zipf, directory, folder = ""):
-
for item in os.listdir(directory):
-
if os.path.isfile(os.path.join(directory, item)):
-
zipf.write(os.path.join(directory, item), folder + os.sep + item)
-
elif os.path.isdir(os.path.join(directory, item)):
-
recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item)
-
These are all good, but IMHO, os.walk rocks and does the hard stuff for you.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Tung Wai Yip |
last post by:
Can I add empty directory using zipfile? When I try to add a directory
it complains that it is not a file.
tung
|
by: Helmut Zeisel |
last post by:
I want to build a static extension of Python using SWIG and VC++ 6.0 as
described in http://www.swig.org/Doc1.3/Python.html#n8 for gcc.
My file is testerl.i:
=========================
%module testerl
extern int hz(int i);
|
by: ralobao |
last post by:
I have this code:
try:
file = zipfile.ZipFile(nome_arquivo)
Gauge.start() #inicia o Gauge
for element in file.namelist():
try:
newFile = open(diretorio + element,"wb")
except:
newFile = open(diretorio + element + '/',"w")
|
by: Phil Galey |
last post by:
Using the following, you can determine the size of a file:
Dim fi As New IO.FileInfo(<Path to file>)
MsgBox(fi.Length)
.... but what about the size of a directory? The IO.DirectoryInfo object
doesn't have a Length property.
In is there a way in VB.NET to determine the size of a directory without
having to resort to importing the...
|
by: WolfsonNYC |
last post by:
Anyone know how to enable Directory Browsing using the Cassini web
server on .Net 2.0 ? Right now it says HTTP Error 403 - Forbidden when
I go to a folder on my web site. Thanks,
JW
| |
by: krithika.sridhar |
last post by:
Hi,
I'm using :
python setup.py bdist_rpm
to create an rpm package to distribute my python app on linux.
When i install the rpm, the files are installed in
/usr/share/python/site-packages/..... directory by default.
|
by: duyanning |
last post by:
I have written a pyhton script that will process data file in current
working directory.
My script is in an different directory to data file.
When I debug this script using pdb within emacs, emacs will change the
current working directory to the directory which include the script,
so my script cannot find the data file.
I think this is the...
|
by: Colin J. Williams |
last post by:
1.I have both 2.5 and 2.6 but both
appear, under Recent Projects, as
pcbuild. It would be helpful if the
Python Version could be indicated.
2.With 2.6, Python compiles and executes
OK but various packages are not
compiled, eg sqlite3.
3.Pythonw compiles OK but not sqlite3.
4.Mike Fletcher suggests an approach...
|
by: cnivas |
last post by:
Hi,
I'm doing a small application in python using mac os x. Now, I want to insert an image in the web application. I have given the image path also... but it shows "?" this symbol.... If the application server runs then the image displays. but if we keep the web application on the net then it is highly impossible to run both the web server and...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |