实际上用于python的StringIO是什么? [英] What is StringIO in python used for in reality?

查看:1109
本文介绍了实际上用于python的StringIO是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是专业人士,而且我一直在理解StringIO的用途。我一直在互联网上寻找一些例子。但是,几乎所有的例子都非常抽象。他们只是展示了如何使用它。但它们都没有显示为什么和在哪种情况下应该/将使用它?
提前致谢

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。不要与stackoverflow上的这个问题混淆: StringIO用法,它比较字符串和StringIo。

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

推荐答案

当你有一些只接受文件的API但你需要使用字符串时使用它。例如,使用Python 2中的 gzip 模块压缩字符串:

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()

这篇关于实际上用于python的StringIO是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆