11

I have a StringIO() file-like object, and I am trying to write it to a ZipFile(), but I get this TypeError:

coercing to Unicode: need string or buffer, cStringIO.StringI found

Here is a sample of the code I am using:

file_like = StringIO()
archive = zipfile.ZipFile(file_like, 'w', zipfile.ZIP_DEFLATED)

# my_file is a StringIO object returned by a remote file storage server.
archive.write(my_file)

The docs say that StringIO() is a file-like class and that ZipFile() can accept a file-like object. Is there something I am missing?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Brian
  • 1,703
  • 3
  • 17
  • 23
  • 3
    The parameter to [`ZipFile.write()`](http://docs.python.org/library/zipfile.html#zipfile.ZipFile.write) is a filename. – Sven Marnach Jun 09 '11 at 21:52
  • 1
    Just found this; is there a typo your second line, or was that your actual code? `ZipFile(file_file` instead of `ZipFile(file_like` – Bogdacutu Dec 28 '11 at 15:20

1 Answers1

13

To add a string to a ZipFile you need to use the writestr method and pass the string from StringIO using getvalue method of the StringIO instance

e.g.

archive.writestr("name of file in zip", my_file.getvalue())

Note you also need to give the name of the string to say where it is placed in the zip file.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117