473,545 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ZIP files

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
from zipfile import *
path= raw_input("\n Please enter the zipfile to be copied: ")

new_zip= ZipFile('someth ing.zip', 'w')
orig_zip=ZipFil e(path, 'r')
zip_files= orig_zip.nameli st()
for file in zip_files:
if file[-2:] == '.c' or file[-2:] == '.h' or file[-4:] == '.exe':
tempfile = open(file,'w')
x = orig_zip.read(f ile)
tempfile.write( x)
tempfile.close( )
new_zip.write(f ile)

So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????
Basically, what I want to do is create a copy of the zip but with a
different name…thanks in advance, Oriana
Jul 18 '05 #1
8 1867
Oriana wrote:
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: [copied by writing to temporary files]
So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????


How about a function like:

import os.path, zipfile

def copy_zip(source _name, dest_name, extensions):
source = zipfile.ZipFile (source_name, 'r')
dest = zipfile.ZipFile (dest_name, 'w', zipfile.ZIP_DEF LATED)
for name in source.namelist ():
if os.path.splitex t(name)[1].lower() in extensions:
contents = source.read(nam e)
dest.writestr(n ame, contents)
dest.close()
source.close()

copy_zip('sourc e.zip', 'dest.zip', {'.c':1, '.h':1, '.exe':1})

If this does the trick for you, try to figure out why you didn't
find "writestr" in the zipfile document. Let us know how we might
improve the document so that we can save work for the next guy.

--Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #2
On 10 Nov 2004 08:05:28 -0800, or**********@th alesesec.com (Oriana)
wrote:
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
from zipfile import *
path= raw_input("\n Please enter the zipfile to be copied: ")

new_zip= ZipFile('someth ing.zip', 'w')
orig_zip=ZipFi le(path, 'r')
zip_files= orig_zip.nameli st()
for file in zip_files:
if file[-2:] == '.c' or file[-2:] == '.h' or file[-4:] == '.exe': # don't do it like this ^^^
if os.path.splitex t(file)[1] in ['.c','.h','.exe ',]:
# this code is cleaner ^^^ tempfile = open(file,'w')
x = orig_zip.read(f ile)
tempfile.write( x)
tempfile.close( )
new_zip.write(f ile)

So far, this code does the work, but I think it's to much work for
just copying entire files…Is there any other way to do this????
Basically, what I want to do is create a copy of the zip but with a
different name…thanks in advance, Oriana


if you want a copy of the zip as is then:

def filecopy(infile , outfile):
i = open(infile, "rb")
o = open(outfile, "wb")
while 1:
s = i.read(8192)
if not s:
break
o.write(s)

You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.

Finally, if you can assume that the files are not huge, why not try
the following one-liner instead:

open(outfile, "wb").write(ope n(infile, "rb").read( ))
if you want to copy certain files from the sourceZIP to a targetZIP
this does not work and you were doing it about right.

cheerz,
Ivo.
Jul 18 '05 #3
Ivo Woltring <Py****@IvoNet. nl> writes:
On 10 Nov 2004 08:05:28 -0800, or**********@th alesesec.com (Oriana)
You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.


This behavior of file objects isn't guaranteed and doesn't happen in
Jython. It's better - and more pythonic - to explicitly close files.

After all, explicit is better than implicit.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #4
Mike Meyer <mw*@mired.or g> wrote in message news:<x7******* *****@guru.mire d.org>...
Ivo Woltring <Py****@IvoNet. nl> writes:
On 10 Nov 2004 08:05:28 -0800, or**********@th alesesec.com (Oriana)
You might wish to try using a larger buffer than 8192 bytes. BTW,
note that Python automatically closes the files since the file objects
are released when the function returns.


This behavior of file objects isn't guaranteed and doesn't happen in
Jython. It's better - and more pythonic - to explicitly close files.

After all, explicit is better than implicit.

<mike


Hmmm... does this mean that

open(filename, 'w').write(file data)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantib...thonutils.html
Jul 18 '05 #5
Michael Foord <fu******@gmail .com> wrote:
Hmmm... does this mean that

open(filename, 'w').write(file data)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.


It's not exactly unsafe -- but you do risk, depending on what
implementation of Python you're dealing with, that the file object will
just stay open until some unknown time in the future (no later than the
end of your program's run;-). This may potentially lead to problems if
your program is long-running or open lots of files, etc.

def write_data(file name, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...
Alex
Jul 18 '05 #6
al*****@yahoo.c om (Alex Martelli) writes:
Michael Foord <fu******@gmail .com> wrote:
Hmmm... does this mean that

open(filename, 'w').write(file data)

is unsafe ? It's so much more convenient when the object is only going
to be used for the single action.


It's not exactly unsafe -- but you do risk, depending on what
implementation of Python you're dealing with, that the file object will
just stay open until some unknown time in the future (no later than the
end of your program's run;-). This may potentially lead to problems if
your program is long-running or open lots of files, etc.

def write_data(file name, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...


I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:

def _write_data(fil ename, data, flags):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

def write_data(file name, data, flags="wb"):
_write_data(fil ename, data, flags)

def write_text(file name, text, flags="w"):
_write_data(fil ename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?

Thomas
Jul 18 '05 #7
Thomas Heller <th*****@python .net> wrote:
...
def write_data(file name, data, flags='w'):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

needs to be coded once, and then makes the operation just as convenient
as doing it inline...
I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:


Hmmm, I thought the optional flags parm would suffice, but you're
probably right it wouldn't...
def _write_data(fil ename, data, flags):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

def write_data(file name, data, flags="wb"):
_write_data(fil ename, data, flags)

def write_text(file name, text, flags="w"):
_write_data(fil ename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?


I'm tempted to add convenience to the write_data wrapper by accepting
some non-str type for data, but that might be going overboard...
Alex
Jul 18 '05 #8
[snip..]
I'd suggest to expand this a bit, and make it working correctly on
windows too, where binary files must be opened with the 'b' flag:

def _write_data(fil ename, data, flags):
fileobject = open(filename, flags)
try: fileobject.writ e(data)
finally: fileobject.clos e()

def write_data(file name, data, flags="wb"):
_write_data(fil ename, data, flags)

def write_text(file name, text, flags="w"):
_write_data(fil ename, data, flags)

plus the corresponding read_data() and read_text() functions.
Hm, add an encoding for unicode, maybe...
Cookbook recipe, or standard lib?

Thomas

Hmm...I have a set of functions as a module - readfile, writefile,
readlines, writelines. My guess is that *everyone* has a similar
module they've written themselves. It can be a PITA cutting and
pasting the functions for a single line job sometimes. It would be a
useful addition to the standard lib.

Regards,

Fuzzy
Jul 18 '05 #9

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

Similar topics

2
14151
by: Mike | last post by:
I am sure that I am making a simple boneheaded mistake and I would appreciate your help in spotting in. I have just installed apache_2.0.53-win32-x86-no_ssl.exe php-5.0.3-Win32.zip Smarty-2.6.7.tar.gz on a system running WindowsXP SP2. Apache and PHP tested out fine. After adding Smarty, I ran the following http://localhost/testphp.php
44
3995
by: Xah Lee | last post by:
here's a large exercise that uses what we built before. suppose you have tens of thousands of files in various directories. Some of these files are identical, but you don't know which ones are identical with which. Write a program that prints out which file are redundant copies. Here's the spec. -------------------------- The program is...
0
6092
by: Tom Lee | last post by:
Hi, I'm new to .NET 2003 compiler. When I tried to compile my program using DEBUG mode, I got the following errors in the C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7 \include\xdebug file as folows. I need help to resolve them ASAP: cl /c /nologo /MDd /W3 /Od /GR /GM /Zi /GX /D "_DEBUG" /D " WIN32" /D "_W INDOWS" /D "_WINDLL"...
18
3145
by: JKop | last post by:
Here's what I know so far: You have a C++ project. You have source files in it. When you go to compile it, first thing the preprocessor sticks the header files into each source file. So now you have your ".cpp" files all ready, without any "#include" or "#define" in them. Let's assume that there's 2 source files in this project,...
3
3081
by: pooja | last post by:
Suppose i have created a class c1 with f1()in c1.cpp and included this c1.cpp in file1.cpp file , which is also having main() by giving the statement #include "c1.cpp". the same i can do by using header file. i can create a class c1 with f1() in c1.h and include this c1.h in file1.cpp by giving the statement #include "c1.h" tell me that...
11
5558
by: ambika | last post by:
Iam just trying to know "c". And I have a small doubt about these header files. The header files just contain the declaration part...Where is the definition for these declarations written??And how does that get linked to our program when we run it??I would appreciate any helpful info..And I would like to thank you for that in advance -ambika
22
2982
by: Daniel Billingsley | last post by:
Ok, I wanted to ask this separate from nospam's ridiculous thread in hopes it could get some honest attention. VB6 had a some simple and fast mechanisms for retrieving values from basic text files, which in turn could be simply and easily maintained with notepad. I understand the benefits of XML, really, but in the case of configuration...
18
2276
by: UJ | last post by:
Folks, We provide custom content for our customers. Currently we put the files on our server and people have a program we provide that will download the files. These files are usually SWF, HTML or JPG files. The problem as I see it - if you know the name of the file, you could download it off the server (currently we are using an HTTP/Get but...
0
1500
by: wal | last post by:
How does one attach files to emails using libgmail? The following code http://pramode.net/articles/lfy/fuse/4.txt works fine when said files are simple text files, but it failes as soon as the files are wild binary files, even attaching the source of an email in a text file (.eml files) failes. What am I missing here? Any hints? The output...
3
5163
by: aRTx | last post by:
I have try a couple of time but does not work for me My files everytime are sortet by NAME. I want to Sort my files by Date-desc. Can anyone help me to do it? The Script <? /* ORIGJINALI
0
7502
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...
0
7434
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...
0
7692
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. ...
1
7457
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...
0
6026
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5360
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...
0
3491
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...
1
1921
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
744
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...

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.