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 38549 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: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
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...
| |