Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a zip an write it to an other file python

Tags:

python

zip

I want to read a file and write it back out. Here's my code:

   file = open( zipname , 'r' )
   content =  file.read() 
   file.close()

   alt = open('x.zip', 'w')
   alt.write(content )
   alt.close()

This doesn't work, why?????

Edit:

The rewritten file is corrupt (python 2.7.1 on windows)

like image 777
Delta Avatar asked Nov 24 '11 01:11

Delta


People also ask

What is ZIP file in Python?

Python's zipfile is a standard library module intended to manipulate ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data.

How do I use ZIP file?

To zip (compress) a file or folder Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.


2 Answers

Read and write in the binary mode, 'rb' and 'wb':

f = open(zipname , 'rb')
content =  f.read() 
f.close()

alt = open('x.zip', 'wb')
alt.write(content )
alt.close()

The reason the text mode didn't work on Windows is that the newline translation from '\r\n' to '\r' mangled the binary data in the zip file.

like image 121
Raymond Hettinger Avatar answered Oct 04 '22 08:10

Raymond Hettinger


From this bit of the manual:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

like image 30
Alastair Maw Avatar answered Oct 04 '22 08:10

Alastair Maw