473,770 Members | 1,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Zipping files/zipfile module

This will probably sound like a very dumb question.

I am trying to zip some files within a directory.

I want to zip all the files within a directory called "temp"
and have the zip archive saved in a directory with temp called ziptemp

I was trying to read up on how to use the zipfile module python
provides, but I cannot seem to find adequate documentation on function
itself.

Perhaps someone could help me in this task?

I am guessing it must be something like the shutile module
something like copy(src,dst)

THank you

Stephen

Aug 2 '06 #1
5 2127
OriginalBrownst er wrote:
I want to zip all the files within a directory called "temp"
and have the zip archive saved in a directory with temp called ziptemp

I was trying to read up on how to use the zipfile module python
provides, but I cannot seem to find adequate documentation on function
itself.

Perhaps someone could help me in this task?
Hello,

This isn't completely tested, but perhaps it will help you get started:

from os import listdir, mkdir
from os.path import join, basename, isfile
from zipfile import ZipFile

def zip_dir(path, output_path, include_hidden= True):
files = [join(path, f) for f in listdir(path) if isfile(join(pat h, f))]
try:
mkdir(output_pa th)
except OSError, e:
if e.errno == 17: # Path exists
pass
zip_file = ZipFile(join(ou tput_path, 'temp.zip'), 'w')
for f in files:
if basename(f).sta rtswith('.') and not include_hidden:
continue
print "Adding %s to archive..." % (f,)
zip_file.write( f)
zip_file.close( )

Use like:
zip_dir('temp', 'temp/ziptemp')

Note that if you want to add the entire contents of a directory
(subdirectories , recursively), you should consider using os.walk or
something similar. This will only add the file contents of the directory.
I'm not sure if the zipfile module provides any nice ways to write
directories to the archive, but I'm assuming it just involves writing an
arcname with a '/' in it (see help(zipfile.Zi pFile)).

--
Brian Beck
Adventurer of the First Order
Aug 2 '06 #2
Brian Beck wrote:
OriginalBrownst er wrote:
I want to zip all the files within a directory called "temp"
and have the zip archive saved in a directory with temp called ziptemp

I was trying to read up on how to use the zipfile module python
provides, but I cannot seem to find adequate documentation on function
itself.

Perhaps someone could help me in this task?

Hello,

This isn't completely tested, but perhaps it will help you get started:

from os import listdir, mkdir
from os.path import join, basename, isfile
from zipfile import ZipFile

def zip_dir(path, output_path, include_hidden= True):
files = [join(path, f) for f in listdir(path) if isfile(join(pat h, f))]
try:
mkdir(output_pa th)
except OSError, e:
if e.errno == 17: # Path exists
pass
zip_file = ZipFile(join(ou tput_path, 'temp.zip'), 'w')
for f in files:
if basename(f).sta rtswith('.') and not include_hidden:
continue
print "Adding %s to archive..." % (f,)
zip_file.write( f)
zip_file.close( )

Use like:
zip_dir('temp', 'temp/ziptemp')

Note that if you want to add the entire contents of a directory
(subdirectories , recursively), you should consider using os.walk or
something similar. This will only add the file contents of the directory.
I'm not sure if the zipfile module provides any nice ways to write
directories to the archive, but I'm assuming it just involves writing an
arcname with a '/' in it (see help(zipfile.Zi pFile)).

--
Brian Beck
Adventurer of the First Order
To avoid calling os.path.join() twice for each filename when you build
the list of files you could write the list comprehension like so:

[n for n in (join(path, f) for f in listdir(path)) if isfile(n)]

Also, you should use the "symbolic" errors from the errno module rather
than hard-coding a constant:

from errno import EEXIST
....
if e.errno == EEXIST: # Path exists

Finally, if your using a single arg with a string interpolation and you
know it'll never be a tuple you needn't wrap it in a tuple:

print "Adding %s to archive..." % f

Aug 2 '06 #3
Simon Forman a écrit :
Brian Beck wrote:
>OriginalBrowns ter wrote:
>>I want to zip all the files within a directory called "temp"
and have the zip archive saved in a directory with temp called ziptemp

I was trying to read up on how to use the zipfile module python
provides, but I cannot seem to find adequate documentation on function
itself.

Perhaps someone could help me in this task?
Hello,

This isn't completely tested, but perhaps it will help you get started:

from os import listdir, mkdir
from os.path import join, basename, isfile
from zipfile import ZipFile

def zip_dir(path, output_path, include_hidden= True):
files = [join(path, f) for f in listdir(path) if isfile(join(pat h, f))]
try:
mkdir(output_pa th)
except OSError, e:
if e.errno == 17: # Path exists
pass
zip_file = ZipFile(join(ou tput_path, 'temp.zip'), 'w')
for f in files:
if basename(f).sta rtswith('.') and not include_hidden:
continue
print "Adding %s to archive..." % (f,)
zip_file.write( f)
zip_file.close( )

Use like:
zip_dir('temp', 'temp/ziptemp')

Note that if you want to add the entire contents of a directory
(subdirectorie s, recursively), you should consider using os.walk or
something similar. This will only add the file contents of the directory.
I'm not sure if the zipfile module provides any nice ways to write
directories to the archive, but I'm assuming it just involves writing an
arcname with a '/' in it (see help(zipfile.Zi pFile)).

--
Brian Beck
Adventurer of the First Order

To avoid calling os.path.join() twice for each filename when you build
the list of files you could write the list comprehension like so:

[n for n in (join(path, f) for f in listdir(path)) if isfile(n)]

Also, you should use the "symbolic" errors from the errno module rather
than hard-coding a constant:

from errno import EEXIST
...
if e.errno == EEXIST: # Path exists

Finally, if your using a single arg with a string interpolation and you
know it'll never be a tuple you needn't wrap it in a tuple:

print "Adding %s to archive..." % f
Other solutions:
you can try the rar command line from WinRar but it's not recommended.
This is a very slow manner to compress file. Or you can try the Bz
module of python.
Aug 2 '06 #4
Ant
Enabling directory recursion:
from os import listdir, mkdir
from os.path import join, basename, isfile
from zipfile import ZipFile

def zip_dir(path, output_path, include_hidden= True):
try:
mkdir(output_pa th)
except OSError, e:
if e.errno == 17: # Path exists
pass
zip_file = ZipFile(join(ou tput_path, 'temp.zip'), 'w')
for root, dirs, files in os.walk(dir):
for f in files:
fp = path.join(root, f)
zip_file.write( fp, fp[len(dir):]) # Write to zip as a
path relative to original dir.
zip_file.close( )
Aug 2 '06 #5
Yves Lange wrote:
Other solutions:
you can try the rar command line from WinRar but it's not recommended.
This is a very slow manner to compress file.
Are you sure? This worked about 4 times faster than the zip command line
utility in Linux, compressing the same files...

--
Brian Beck
Adventurer of the First Order
Aug 2 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
9785
by: Doug Tolton | last post by:
Is there a simple way to zip and unzip files? I'm looking for something along the lines of: zfile = zipfile(r'c:\somefile.zip') zfile.extract(r'c:\somefiles') I've looked at the documentation for zlib and zipfile, and they seem pretty comprehensive, but also extremely low level. If needed, I can probably make a workable component from them, but I was wondering if
8
1884
by: Oriana | last post by:
Hi! I'm beginning to use the zipfile module in Python and I'm confused about something. I am trying to extract certain files from one zip and copy them into another one. This is the code I‘ve got so far: import string import os, re
5
5602
by: Lorn | last post by:
Is there a limitation with python's zipfile utility that limits the size of a file that can be extracted? I'm currently trying to extract 125MB zip files with files that are uncompressed to > 1GB and am receiving memory errors. Indeed my ram gets maxed during extraction and then the script quits. Is there a way to spool to disk on the fly, or is necessary that python opens the entire file before writing? The code below iterates through a...
4
1426
by: OriginalBrownster | last post by:
Hi There. I'm very new to python, and I have been using the TurboGears Framework to use python to power my application. I have a class which handles the upload of a file to a directory called "uploads", which is hosted on a server. my problems is that when I want to download that file from the server I want to zip the files selected. but how does a user specify where they
5
2915
by: Jandre | last post by:
Hi I am a python novice and I am trying to write a python script (most of the code is borrowed) to Zip a directory containing some other directories and files. The script zips all the files fine but when it tries to zip one of the directories it fails with the following error: "IOError: Permission denied: 'c:\\aaa\\temp'" The script I am using is:
8
3943
by: =?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B | last post by:
I made a C/S network program, the client receive the zip file from the server, and read the data into a variable. how could I process the zipfile directly without saving it into file. In the document of the zipfile module, I note that it mentions the file-like object? what does it mean? class ZipFile( file]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object.
2
5454
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) OverflowError: long it too large to...
3
4323
by: dp_pearce | last post by:
Hi all, I have come across an error while using zipfile and I can't seem to find somewhere that explains the problem. My script needs to be able to take text files from one drive and add them to zip files on another drive. The following seems to work just fine. import zipfile # write test file in working directory directory
1
1325
by: Bouzy | last post by:
I wrote this script... #!/usr/bin/python # Filename: backup_zip.py import os, zipfile, time, datetime, glob from os.path import splitext, relpath, split r = 1 cwd = os.getcwd()
0
9617
marktang
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10257
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
jinu1996
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9904
tracyyun
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7456
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.