StringIO 模块的使用. 它实现了一个工作在内存的文件对象 (内存文件). 在大多需要标准文件对象的地方都可以使用它来替换.
使用 StringIO 模块从内存文件读入内容
复制代码 代码示例:
import StringIO
MESSAGE = "That man is depriving a village somewhere of a computer scientist."
file = StringIO.StringIO(MESSAGE)
print file.read()
That man is depriving a village somewhere of a computer scientist.
StringIO 类实现了内建文件对象的所有方法, 此外还有 getvalue 方法用来返回它内部的字符串值
使用 StringIO 模块向内存文件写入内容
复制代码 代码示例:
import StringIO
file = StringIO.StringIO()
file.write("This man is no ordinary man. ")
file.write("This is Mr. F. G. Superman.")
print file.getvalue()
This man is no ordinary man. This is Mr. F. G. Superman.
使用 StringIO 模块捕获输出
复制代码 代码示例:
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())
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
cStringIO 是一个可选的模块, 是 StringIO 的更快速实现. 它的工作方式和 StringIO 基本相同, 但是它不可以被继承
使用 cStringIO 模块
复制代码 代码示例:
import cStringIO
MESSAGE = "That man is depriving a village somewhere of a computer scientist."
file = cStringIO.StringIO(MESSAGE)
print file.read()
That man is depriving a village somewhere of a computer scientist.
为了让代码尽可能快, 但同时保证兼容低版本的 Python ,你可以使用一个小技巧在 cStringIO 不可用时启用 StringIO 模块,退至 StringIO。
复制代码 代码示例:
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
print StringIO
<module 'StringIO' (built-in)>
mmap 模块提供了操作系统内存映射函数的接口, 映射区域的行为和字符串对象类似, 但数据是直接从文件读取的.
使用 mmap 模块
复制代码 代码示例:
import mmap
import os
filename = "samples/sample.txt"
file = open(filename, "r+")
size = os.path.getsize(filename)
data = mmap.mmap(file.fileno(), size)
# basics
print data
print len(data), size
# use slicing to read from the file
# 使用切片操作读取文件
print repr(data[:10]), repr(data[:10])
# or use the standard file interface
# 或使用标准的文件接口
print repr(data.read(10)), repr(data.read(10))
<mmap object at 008A2A10>
302 302
'We will pe' 'We will pe'
'We will pe' 'rhaps even'
在 Windows 下, 这个文件必须以既可读又可写的模式打开( `r+` , `w+` , 或 `a+` ), 否则 mmap 调用会失败.
对映射区域使用字符串方法和正则表达式
复制代码 代码示例:
import mmap
import os, string, re
def mapfile(filename):
file = open(filename, "r+")
size = os.path.getsize(filename)
return mmap.mmap(file.fileno(), size)
data = mapfile("samples/sample.txt")
# search
index = data.find("small")
print index, repr(data[index-5:index+15])
# regular expressions work too!
m = re.search("small", data)
print m.start(), m.group()
43 'only small 15 12modules '
43 small