module: zipfile.writestr - line endings issue

Paul Carter pacman128 at gmail.com
Tue Aug 14 15:49:16 EDT 2007


On Aug 14, 1:32 pm, towers <damondo... at googlemail.com> wrote:
> Thanks - your code works for me also.
>
> But I still get the issue when I read the file directly and add it to
> the archive.
>
> Say if I:
>
> 1. Use the test.csv file created with your code - currently the line
> endings look good (viewed in notepad on Win XP)
> 2. Run the following code:
>
> # begin code
> import zipfile
> import os.path
>
> # Now, create the zipfile
> dfile = open('test.csv', 'r')
> zip_file = zipfile.ZipFile(r'C:\temp\ice\line endings\test.zip', 'w',
> zipfile.ZIP_DEFLATED)
> zip_file.writestr('test.csv',dfile.read())
> dfile.close()
> zip_file.close()
>
> 3. Then extract the file and the file endings have been corrupted. Now
> one long line in notepad. (Other programs interpret correctly though.)
>
> Maybe the issue lies with this way (i.e. dfile.read()) of writing the
> file to the archive...possibly.
>
> Damon
>

Please don't top post.

The problem is with how you are opening the file. You need to open in
binary mode if you wish to read your file unaltered. Also, file() is
preferred over open() these days I think. Use:

dfile = file('test.csv', 'rb')

--
Paul Carter




More information about the Python-list mailing list