python标准库介绍——18 StringIO 模块详解

复制代码
==StringIO 模块==


[Example 2-8 #eg-2-8] 展示了 ``StringIO`` 模块的使用. 它实现了一个工作在内存的文件对象
(内存文件). 在大多需要标准文件对象的地方都可以使用它来替换.

====Example 2-8. 使用 StringIO 模块从内存文件读入内容====[eg-2-8]

```
File: stringio-example-1.py

import StringIO

MESSAGE = "That man is depriving a village somewhere of a computer scientist."

file = StringIO.StringIO(MESSAGE)

print file.read()

*B*That man is depriving a village somewhere of a computer scientist.*b*
```

``StringIO`` 类实现了内建文件对象的所有方法, 此外还有 ``getvalue`` 方法用来返回它内部的字符串值. 
[Example 2-9 #eg-2-9] 展示了这个方法.

====Example 2-9. 使用 StringIO 模块向内存文件写入内容====[eg-2-9]

```
File: stringio-example-2.py

import StringIO

file = StringIO.StringIO()
file.write("This man is no ordinary man. ")
file.write("This is Mr. F. G. Superman.")

print file.getvalue()

*B*This man is no ordinary man. This is Mr. F. G. Superman.*b*
```

``StringIO`` 可以用于重新定向 Python 解释器的输出, 如 [Example 2-10 #eg-2-10] 所示.

====Example 2-10. 使用 StringIO 模块捕获输出====[eg-2-10]

```
File: stringio-example-3.py

import StringIO
import string, sys

stdout = sys.stdout

sys.stdout = file = StringIO.StringIO()

print """
According to Gbaya folktales, trickery and guile
are the best ways to defeat the python, king of
snakes, which was hatched from a dragon at the
world's start. -- National Geographic, May 1997
"""

sys.stdout = stdout

print string.upper(file.getvalue())

*B*ACCORDING TO GBAYA FOLKTALES, TRICKERY AND GUILE
ARE THE BEST WAYS TO DEFEAT THE PYTHON, KING OF
SNAKES, WHICH WAS HATCHED FROM A DRAGON AT THE
WORLD'S START. -- NATIONAL GEOGRAPHIC, MAY 1997*b*
```
复制代码

 

posted @   淋哥  阅读(2583)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示