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 38538 bvdet 2,851
Expert Mod 2GB
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
Expert Mod 2GB
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...
|
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 =...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
| |