473,765 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Script to make Windows XP-readable ZIP file

pac
I'm preparing to distribute a Windows XP Python program and some
ancillary files,
and I wanted to put everything in a .ZIP archive. It proved to be
inordinately
difficult and I thought I would post my solution here. Is there a
better one?

Suppose you have a set of files in a directory c:\a\b and some
additional
files in c:\a\b\subdir. Using a Python script, you would
like to make a Windows-readable archive (.zip) that preserves this
directory structure, and where the root directory of the archive is
c:\a\b. In other words, all the files from c:\a\b appear in the
archive
without a path prefix, and all the files in c:\a\b\subdir have a path
prefix of \subdir.

This looks like it should be easy with module zipfile and the handy
function os.walk. Create a zip file, call os.walk, and add the files
to
the archive like so:

import os
import zipfile

z =
zipfile.ZipFile (r"c:\a\b\myzip .zip",mode="w", compression=zip file.ZIP_DEFLAT ED)

for dirpath,dirs,fi les in os.walk(r"c:\a\ b"):
for a_file in files:
a_path = os.path.join(di rpath,a_file)
z.write(a_path) # Change, see below
z.close()

This creates an archive that can be read by WinZip or by another Python
script
that uses zipfile. But when you try to view it with the Windows
compressed folder
viewer it will appear empty. If you try to extract the files anyway
(because
you know they are really there), you get a Windows Security Warning and
XP
refuses to decompress the folder - XP is apparently afraid it might be
bird flu
or something.

If you change the line marked #Change to "z.write(a_path ,file)",
explicitly naming
each file, now the compressed folder viewer will show all the files in
the archive.
XP will not treat it like a virus and it will extract the files.
However, the
archive does not contain a subdirectory; all the files are in a single
directory.

Some experimentation suggests that Windows does not like any filename
in the
archive that begins with either a drive designator like c:, or has a
path containing
a leading slash like "\a\b\afile.txt ". Relative paths like
"subdir\afile.t xt" are
okay, and cause the desired behavior when the archive is extracted,
e.g., a new directory subdir is created and afile.txt is placed in it.

Since the method ZipFile.write needs a valid pathname for each file,
the correct
solution to the original problem entails messing around with the OS's
current
working directory. Position the CWD in the desired base directory of
the archive,
add the files to the archive using their relative pathnames, and put
the CWD back
where it was when you started:

import os
import zipfile

z =
zipfile.ZipFile (r"c:\a\b\myzip .zip",mode="w", compression=zip file.ZIP_DEFLAT ED)

cwd = os.getcwd()
os.chdir(base_d ir)
try:
for dirpath,dirs,fi les in os.walk(''): # This starts the walk at
the CWD
for a_file in files:
a_path = os.path.join(di rpath,a_file)
z.write(a_path, a_path) # Can the second argument be
omitted?
z.close()
finally:
os.chdir(cwd)

This produces an archive that can be extracted by Windows XP using its
built-in
capability, by WinZip, or by another Python script. Now that I have
the solution it
seems to make sense, but it wasn't at all obvious when I started.

Paul Cornelius

May 19 '06 #1
12 5746
i am in win2000
"z.write(a_path ,a_path)" may change to "z.write(a_path )"
but the dirpath is not in zipfile
who can tell me?

May 19 '06 #2
pac wrote:
Suppose you have a set of files in a directory c:\a\b and some
additional
files in c:\a\b\subdir. Using a Python script, you would
like to make a Windows-readable archive (.zip) that preserves this
directory structure, and where the root directory of the archive is
c:\a\b. In other words, all the files from c:\a\b appear in the
archive
without a path prefix, and all the files in c:\a\b\subdir have a path
prefix of \subdir.

This looks like it should be easy with module zipfile and the handy
function os.walk. Create a zip file, call os.walk, and add the files
to
the archive like so:

import os
import zipfile

z =
zipfile.ZipFile (r"c:\a\b\myzip .zip",mode="w", compression=zip file.ZIP_DEFLAT ED)

for dirpath,dirs,fi les in os.walk(r"c:\a\ b"):
for a_file in files:
a_path = os.path.join(di rpath,a_file)
z.write(a_path) # Change, see below
z.close()
(Aside: be careful not to use tabs when posting. I suspect the f-bot
will be here to tell you that the above code doesn't work.)
Some experimentation suggests that Windows does not like any filename
in the
archive that begins with either a drive designator like c:, or has a
path containing
a leading slash like "\a\b\afile.txt ". Relative paths like
"subdir\afile.t xt" are
okay, and cause the desired behavior when the archive is extracted,
e.g., a new directory subdir is created and afile.txt is placed in it.

Since the method ZipFile.write needs a valid pathname for each file,
the correct
solution to the original problem entails messing around with the OS's
current
working directory.
ZipFile.write takes an optional second argument for the archive
filename. You could have done something like this (untested):

for dirpath,dirs,fi les in os.walk(r"c:\a\ b"):
for a_file in files:
a_path = os.path.join(di rpath,a_file)
z_path = a_path[7:] # or whatever
z.write(a_path, z_path)
z.close()

And maybe use a little helper function instead of the string slice to
make it more robust (it violates DRY, and I'm not happy to assume the
dirpath returned by os.walk has exactly the same prefix as the
argument).
Position the CWD in the desired base directory of
the archive,
add the files to the archive using their relative pathnames, and put
the CWD back
where it was when you started:


This may be the best way anyways, unless you have some reason to not
change the current directory.
Carl Banks

May 19 '06 #3
"pac" <pa*@fernside.c om> wrote:
I'm preparing to distribute a Windows XP Python program and some
ancillary files,
and I wanted to put everything in a .ZIP archive. It proved to be
inordinately
difficult and I thought I would post my solution here. Is there a
better one?


heresy maybe, but I use Ant to do such things (with my Perl projects):
http://ant.apache.org/

--
John MexIT: http://johnbokma.com/mexit/
personal page: http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
May 19 '06 #4
my code can work, like below:

import os
import zipfile
z =
zipfile.ZipFile (r"c:\text.zip" ,mode="w",compr ession=zipfile. ZIP_DEFLATED)
cwd = os.getcwd()
try:
for dirpath,dirs,fi les in os.walk(cwd):
for file in files:
z_path = os.path.join(di rpath,file)
z.write(z_path)
z.close()
finally:
if z:
z.close()

that is true
but the archive include the absolute path .
can you give me a way to build it with relative path.

May 19 '06 #5
aha
we want to do it with python
don't use ant

May 19 '06 #6
"softwindow " <so********@gma il.com> wrote:
aha
we want to do it with python
don't use ant


:-D

I want to do a lot with Perl, but sometimes it's better to use the right
tool for the job. And I think that Ant is better at for what I use it
compared to a home brew tool I could make. Be careful with "Not Invented
Here".

--
John MexIT: http://johnbokma.com/mexit/
personal page: http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
May 19 '06 #7
Carl Banks is right

May 19 '06 #8
aha
now it's right like this:

import os
import zipfile
z =
zipfile.ZipFile (r"c:\text.zip" ,mode="w",compr ession=zipfile. ZIP_DEFLATED)
cwd = os.getcwd()
try:
for dirpath,dirs,fi les in os.walk(cwd):
for file in files:
z_path = os.path.join(di rpath,file)
start = cwd.rfind(os.se p)+1
z.write(z_path, z_path[start:])
z.close()
finally:
if z:
z.close()

May 19 '06 #9
import os
import zipfile
z =
zipfile.ZipFile (r"c:\text.zip" ,mode="w",compr ession=zipfile. ZIP_DEFLATED)
cwd = os.getcwd()
try:
for dirpath,dirs,fi les in os.walk(cwd):
for file in files:
z_path = os.path.join(di rpath,file)
start = cwd.rfind(os.se p)+1
z.write(z_path, z_path[start:])
z.close()
finally:
if z:
z.close()
*************** ******
can work

May 19 '06 #10

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

Similar topics

8
2766
by: Jonathan Heath | last post by:
Hi all, I have created an ASP script that enters data into an Access Database. My problem is that I'd like this script to run when the computer is shutdown or the user logs off. I think this would be simple enough if the ASP didn't have any user input, but it does.
7
1225
by: bob | last post by:
I haven't used Visual Studio (2003) in several months. I fired it up and tried to create a new C# class library project. Nothing happens. Nothing appears in the Solution Explorer and nothing appears in the directory where I told VS to make the project. I uninstalled VS and reinstalled it. Same behavior. I don't know what to do. Any advice?
1
1662
by: JMMB | last post by:
The <script> tags work in a htm page, but when I convert it to .aspx page, it stops working? I get a IE script error. What might be the mistake here? thanks, <HTML> <HEAD> <TITLE> Teste Menu </TITLE>
5
9025
by: Brian Henry | last post by:
I have this script Dim query As New ManagementObjectSearcher("Select * from Select * from Win32_Product") Debug.Write(query.Get().Count) For Each mo As ManagementObject In query.Get Me.ListBox1.Items.Add(mo("Name"))
4
5943
by: aramsey | last post by:
I have a javascript program that works fine under Firefox and on IE when running XP, but is having a problem with IE running under Windows 2000 Pro. On my personal XP development machine I have the Microsoft Script Editor and I can set a breakpoint, step through code, inspect variables, etc... with no problem. On a machine where I am trying to debug this problem I am running Windows 2000 Pro with IE 6. I installed the Microsoft...
6
10067
by: sam | last post by:
Hi, I want to compile and test php script in my pc without using internet or web site which is online ? Do you have any idea about it? It is possible to do that ?
48
3334
by: Nathan Sokalski | last post by:
Ever since I found out that they didn't give us a way to install both IE6 and IE7 on the same machine, I have been more frustrated and annoyed with Microsoft than I ever have been with any company (and for someone who has loved Microsoft as much as me, that takes something pretty bad!). I am a web developer, and only have access to one computer, which makes it hard to test for both IE6 and IE7. But even for people that have access to...
1
1952
by: ScriptPepe | last post by:
Hello Everybody. A pleasure to be here. I need a script for reinitiate my system . Actually I have four systems (all the same xp pro). Manually My Pc - properties - advanced options - recuperation (configuration) - predeterminated operating system (selection). reinitiation - accept I would like automate this process. I change frecuently of system reinitiating.
4
4917
by: Randy Webb | last post by:
This post was originally made in microsoft.public.scripting.jscript by Michael Harris and I am reposting it here for the people who don't/can't subscribe to the microsoft groups. The original thread can be read here: <URL: http://groups.google.com/group/microsoft.public.scripting.jscript/browse_frm/thread/91bd7c8dfe3c8a9f/a80a764bfb34d2ee#a80a764bfb34d2ee> Windows Script 5.7 for Windows 2000/XP/Server 2003 Download details: Windows...
20
5298
drhowarddrfine
by: drhowarddrfine | last post by:
I have a web application that will generate a web page and tuck it in a top secret location on the server. I need a Windows XP box to be able to run a program in the background to check to see if the page is there and fetch this page from the server and print it on the Windows printer. It should poll the server every minute or two. XP Pro is available but would rather it run on XP Home. The page is located in an unpublished area of the...
0
9568
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
9398
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10160
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...
1
9951
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7378
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
6649
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();...
1
3924
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
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
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.