473,883 Members | 1,639 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with zipfile and newlines

I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.

The code I'm using is something like:

from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')

I'm using Python version 2.5. Has anyone else had this problem
before, or know how to fix it?

Thanks,

Neil
Mar 10 '08 #1
5 5179
On Mar 10, 8:31 pm, "Neil Crighton" <neilcrigh...@g mail.comwrote:
I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.

The code I'm using is something like:

from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')
"Too many newlines" is fixed by removing all instances of '\r'. What
are you calling a newline? '\r'??

How do you know there are too many thingies? What operating system
were the original files created on?

When you do:
# using a more meaningful name :-)
extractedfileco ntents = z.read('filenam e_in_zippedfile ')
then:
print repr(extractedf ilecontents)
what do you see at the end of what you regard as each line:
(1) \n
(2) \r\n
(3) \r
(4) something else
?

Do you fiddle with extractedfileco ntents (other than trying to fix it)
before writing it to the file?

When you write out a text file,
do you do:
open('foo.txt', 'w').write(extr actedfileconten ts)
or
open('foo.txt', 'wb').write(ext ractedfileconte nts)
?

When you write out a binary file,
do you do:
open('foo.txt', 'w').write(extr actedfileconten ts)
or
open('foo.txt', 'wb').write(ext ractedfileconte nts)
?
Mar 10 '08 #2
"Neil Crighton" <ne**********@g mail.comwrote:
I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.

The code I'm using is something like:

from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')

I'm using Python version 2.5. Has anyone else had this problem
before, or know how to fix it?

Thanks,
Zip files aren't text. Try opening the zipfile file in binary mode:

open('zippedfil e.zip', 'rb')

Mar 10 '08 #3
On Mar 10, 11:14 pm, Duncan Booth <duncan.bo...@i nvalid.invalid>
wrote:
"Neil Crighton" <neilcrigh...@g mail.comwrote:
I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.
The code I'm using is something like:
from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')
I'm using Python version 2.5. Has anyone else had this problem
before, or know how to fix it?
Thanks,

Zip files aren't text. Try opening the zipfile file in binary mode:

open('zippedfil e.zip', 'rb')
Good pickup, but that indicates that the OP may have *TWO* problems,
the first of which is not posting the code that was actually executed.

If the OP actually executed the code that he posted, it is highly
likely to have died in a hole long before it got to the z.read()
stage, e.g.
>>import zipfile
z = zipfile.ZipFile (open('foo.zip' ))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python25\li b\zipfile.py", line 346, in __init__
self._GetConten ts()
File "C:\python25\li b\zipfile.py", line 366, in _GetContents
self._RealGetCo ntents()
File "C:\python25\li b\zipfile.py", line 404, in _RealGetContent s
centdir = struct.unpack(s tructCentralDir , centdir)
File "C:\python25\li b\struct.py", line 87, in unpack
return o.unpack(s)
struct.error: unpack requires a string argument of length 46
>>z = zipfile.ZipFile (open('foo.zip' , 'rb')) # OK
z = zipfile.ZipFile ('foo.zip', 'r') # OK
If it somehow made it through the open stage, it surely would have
blown up at the read stage, when trying to decompress a contained
file.

Cheers,
John
Mar 10 '08 #4
Sorry my initial post was muddled. Let me try again.

I've got a zipped archive that I can extract files from with my
standard archive unzipping program, 7-zip. I'd like to extract the
files in python via the zipfile module. However, when I extract the
file from the archive with ZipFile.read(), it isn't the same as the 7-
zip-extracted file. For text files, the zipfile-extracted version has
'\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't
tried comparing binary files via the two extraction methods yet.

Regarding the code I posted; I was writing it from memory, and made a
mistake. I didn't use:

z = zipfile.ZipFile (open('foo.zip' , 'r'))

I used this:

z = zipfile.ZipFile ('foo.zip')

But Duncan's comment was useful, as I generally only ever work with
text files, and I didn't realise you have to use 'rb' or 'wb' options
when reading and writing binary files.

To answer John's questions - I was calling '\r' a newline. I should
have said carriage return. I'm not sure what operating system the
original zip file was created on. I didn't fiddle with the extracted
file contents, other than replacing '\r' with ''. I wrote out all the
files with open('outputfil e','w') - I seems that I should have been
using 'wb' when writing out the binary files.

Thanks for the quick responses - any ideas why the zipfile-extracted
files and 7-zip-extracted files are different?

On Mar 10, 9:37 pm, John Machin <sjmac...@lexic on.netwrote:
On Mar 10, 11:14 pm, Duncan Booth <duncan.bo...@i nvalid.invalid>
wrote:
"Neil Crighton" <neilcrigh...@g mail.comwrote:
I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.
The code I'm using is something like:
from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')
I'm using Python version 2.5. Has anyone else had this problem
before, or know how to fix it?
Thanks,
Zip files aren't text. Try opening the zipfile file in binary mode:
open('zippedfil e.zip', 'rb')

Good pickup, but that indicates that the OP may have *TWO* problems,
the first of which is not posting the code that was actually executed.

If the OP actually executed the code that he posted, it is highly
likely to have died in a hole long before it got to the z.read()
stage, e.g.
>import zipfile
z = zipfile.ZipFile (open('foo.zip' ))

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python25\li b\zipfile.py", line 346, in __init__
self._GetConten ts()
File "C:\python25\li b\zipfile.py", line 366, in _GetContents
self._RealGetCo ntents()
File "C:\python25\li b\zipfile.py", line 404, in _RealGetContent s
centdir = struct.unpack(s tructCentralDir , centdir)
File "C:\python25\li b\struct.py", line 87, in unpack
return o.unpack(s)
struct.error: unpack requires a string argument of length 46
>z = zipfile.ZipFile (open('foo.zip' , 'rb')) # OK
z = zipfile.ZipFile ('foo.zip', 'r') # OK

If it somehow made it through the open stage, it surely would have
blown up at the read stage, when trying to decompress a contained
file.

Cheers,
John
Mar 11 '08 #5
I think I've worked it out after reading the 'Binary mode for files'
section of http://zephyrfalcon.org/labs/python_pitfalls.html

zipfile extracts as file as a binary series of characters, and I'm
writing out this binary file as a text file with open('foo','w') .
Normally Python converts a '\n' in a text file to whatever the
platform-dependent indication of a new line is ('\n' on Unix, '\r\n'
on Windows, '\r' on Macs). So it sees '\r\n' in the binary file and
converts it to '\r\r\n' for the text file.

The upshot of this is that writing out the zipfile-extracted files
with open('foo','wb' ) instead of open('foo','w') solves my problem.

On Mar 11, 8:43 pm, neilcrigh...@gm ail.com wrote:
Sorry my initial post was muddled. Let me try again.

I've got a zipped archive that I can extract files from with my
standard archive unzipping program, 7-zip. I'd like to extract the
files in python via the zipfile module. However, when I extract the
file from the archive with ZipFile.read(), it isn't the same as the 7-
zip-extracted file. For text files, the zipfile-extracted version has
'\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't
tried comparing binary files via the two extraction methods yet.

Regarding the code I posted; I was writing it from memory, and made a
mistake. I didn't use:

z = zipfile.ZipFile (open('foo.zip' , 'r'))

I used this:

z = zipfile.ZipFile ('foo.zip')

But Duncan's comment was useful, as I generally only ever work with
text files, and I didn't realise you have to use 'rb' or 'wb' options
when reading and writing binary files.

To answer John's questions - I was calling '\r' a newline. I should
have said carriage return. I'm not sure what operating system the
original zip file was created on. I didn't fiddle with the extracted
file contents, other than replacing '\r' with ''. I wrote out all the
files with open('outputfil e','w') - I seems that I should have been
using 'wb' when writing out the binary files.

Thanks for the quick responses - any ideas why the zipfile-extracted
files and 7-zip-extracted files are different?

On Mar 10, 9:37 pm, John Machin <sjmac...@lexic on.netwrote:
On Mar 10, 11:14 pm, Duncan Booth <duncan.bo...@i nvalid.invalid>
wrote:
"Neil Crighton" <neilcrigh...@g mail.comwrote:
I'm using the zipfile library to read a zip file in Windows, and it
seems to be adding too many newlines to extracted files. I've found
that for extracted text-encoded files, removing all instances of '\r'
in the extracted file seems to fix the problem, but I can't find an
easy solution for binary files.
The code I'm using is something like:
from zipfile import Zipfile
z = Zipfile(open('z ippedfile.zip') )
extractedfile = z.read('filenam e_in_zippedfile ')
I'm using Python version 2.5. Has anyone else had this problem
before, or know how to fix it?
Thanks,
Zip files aren't text. Try opening the zipfile file in binary mode:
open('zippedfil e.zip', 'rb')
Good pickup, but that indicates that the OP may have *TWO* problems,
the first of which is not posting the code that was actually executed.
If the OP actually executed the code that he posted, it is highly
likely to have died in a hole long before it got to the z.read()
stage, e.g.
>>import zipfile
>>z = zipfile.ZipFile (open('foo.zip' ))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python25\li b\zipfile.py", line 346, in __init__
self._GetConten ts()
File "C:\python25\li b\zipfile.py", line 366, in _GetContents
self._RealGetCo ntents()
File "C:\python25\li b\zipfile.py", line 404, in _RealGetContent s
centdir = struct.unpack(s tructCentralDir , centdir)
File "C:\python25\li b\struct.py", line 87, in unpack
return o.unpack(s)
struct.error: unpack requires a string argument of length 46
>>z = zipfile.ZipFile (open('foo.zip' , 'rb')) # OK
>>z = zipfile.ZipFile ('foo.zip', 'r') # OK
If it somehow made it through the open stage, it surely would have
blown up at the read stage, when trying to decompress a contained
file.
Cheers,
John
Mar 11 '08 #6

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

Similar topics

1
2437
by: Bert | last post by:
Hello, I'm using a script to handle downloads of files, it seems to work but I'm getting random server errors. I guess it has something to do with the filesize. The script will be needed to download files of 6 to 8 MB but I've only tested with files from 0.5 to 2.5 MB. I get the following error: The server closed the connection while reading the response. Contact your system administrator. (SERVER_RESPONSE_CLOSE)
2
1553
by: Renzo | last post by:
Hi, I'm working to create a backup function for a software; in particular, from a directory with 12300 files (Jpg, medium size = 250KB / total size = 2.90GB), i have to create a zip file. I've decided to use the standard "zipfile" library to do that. This is the code: zipName = path.join(config.get('server.xbakPath'), 'backup.zip') fileExport = zipfile.ZipFile(zipName,'w',zipfile.ZIP_DEFLATED)
1
4224
by: Waitman Gobble | last post by:
Hello, I am new to Python. I am having trouble with zipfile.py. On a Linux machine with python 2.4.2 I have trouble opening a zipfile. Python is complaining about the bit where it does a seek(-22,2). Looks to me like zipfile.py is trying to come back 22 bytes from the end of file. # python
8
3015
by: Xela | last post by:
Hi A have a very annoying problem. I have written java strored procedures for DB2 v8.1. Their deployement and usage is fine as long as the server is a Windows one. But under Solaris 8 and Linux RH, the call of sqlj.install_jar fails. It correctly create a directiory with the correct schema name, but the jar is not copied in it. The error is "Permission Denied" SQLSTATE 38501 and in the log, we can see that calling sqlejReadJar fails in...
0
2020
by: Juan Carlos Huitzache | last post by:
Hi, I am trying to build a very simple Java stored procedure on DB2 V8.2 for AIX. I use the WSAD 5.1 or the DB2 Development Center with the same result: C:\Program Files\SQLLIB\java\jdk\bin\jar cf SQL50107055425339.jar com\ibm\xseries\PROCEDURE1.class DB2INST1.PROCEDURE1 - Jar file created.
5
2465
by: Waguy | last post by:
Hi all, I am new to python and want to create a process to unzip large numbers of zip files I get from a SOAP application. The files all have a ZIP extention and can be unzipped using WinZip. However when I try opening the files using zlib or zipfile modules I get the following error: Traceback (most recent call last):
11
7628
by: Hari Sekhon | last post by:
I do import zipfile zip=zipfile.ZipFile('d:\somepath\cdimage.zip') zip.namelist() then either of the two: A) file('someimage.iso','w').write(zip.read('someimage.iso'))
3
4903
bvdet
by: bvdet | last post by:
Following is an example that may provide a solution to you: """ Function makeArchive is a wrapper for the Python class zipfile.ZipFile 'fileList' is a list of file names - full path each name 'archive' is the file name for the archive with a full path """ import zipfile, os def makeArchive(fileList, archive):
8
3954
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.
0
11151
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
10752
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...
1
10858
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,...
0
10420
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...
0
9582
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7974
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
7134
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
5996
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3238
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.