module: zipfile.writestr - line endings issue

programmer.py at gmail.com programmer.py at gmail.com
Tue Aug 14 12:55:04 EDT 2007


On Aug 14, 11:04 am, towers <damondo... at googlemail.com> wrote:
> Hi
>
> I'm probably doing something stupid but I've run into a problem
> whereby I'm trying to add a csv file to a zip archive - see example
> code below.
>
> The csv just has several rows with carriage return line feeds (CRLF).
>
> However after adding it to an archive and then decompressing the line
> endings have been converted to just line feeds (LF).
>
> Does anyone know if this is a bug or am I just doing something wrong?
>
> Many Thanks,
> Damon
>
> ****************************************************************************
> import zipfile
>
> zipFile = zipfile.ZipFile('LocalZipFile.zip', 'a',
> zipfile.ZIP_DEFLATED)
> dfile = open('LocalCSVFile.csv', 'r')
> zipFile.writestr('test.csv',dfile.read())
> dfile.close()
> zipFile.close()
> ****************************************************************************

Line endings will drive you up the wall.  Anyway, the python zipfile
library does not seem to be doing any translations.  The code below
works for me.

# begin code
import zipfile
import os.path

# First create some work data...
csv_data = '1,2\r\n3,4\r\n5,6\r\n'

# Now, create the zipfile
zip_file = zipfile.ZipFile(r'c:\tmp\test.zip', 'w',
zipfile.ZIP_DEFLATED)
zip_file.writestr('test.csv',csv_data)
zip_file.close()

# Now, extract the info
zip_file = zipfile.ZipFile(r'c:\tmp\test.zip')
assert len(zip_file.read('test.csv')) == len(csv_data)
# end code

Something else must be tweaking your line endings.
HTH!

jw




More information about the Python-list mailing list