Warm tip: This article is reproduced from serverfault.com, please click

What is StringIO in python used for in reality?

发布于 2011-11-03 14:22:45

I am not a pro and I have been scratching my head over understanding what exactly StringIO is used for. I have been looking around the internet for some examples. However, almost all of the examples are very abstract. And they just show "how" to use it. But none of them show "why" and "in which circumstances" one should/will use it? Thanks in advance

p.s. not to be confused with this question on stackoverflow: StringIO Usage which compares string and StringIo.

Questioner
Hossein
Viewed
0
Petr Viktorin 2016-01-08 23:31:19

It's used when you have some API that only takes files, but you need to use a string. For example, to compress a string using the gzip module in Python 2:

import gzip
import StringIO

stringio = StringIO.StringIO()
gzip_file = gzip.GzipFile(fileobj=stringio, mode='w')
gzip_file.write('Hello World')
gzip_file.close()

stringio.getvalue()