nic*_*ine 3 python string file-io file
我有一个函数期望一个文件对象,简化示例:
def process(fd):
print fd.read()
Run Code Online (Sandbox Code Playgroud)
通常称为:
fd = open('myfile', mode='r')
process(fd)
Run Code Online (Sandbox Code Playgroud)
我无法更改此功能,并且我已经在内存中拥有该文件的内容.有没有办法convert将文件内容写入文件对象而不将其写入磁盘,所以我可以这样做:
contents = 'The quick brown file'
fd = convert(contents) # ??
process(fd)
Run Code Online (Sandbox Code Playgroud)
你可以这样做StringIO:
该模块实现了一个类文件类StringIO,它读写字符串缓冲区(也称为内存文件).
from StringIO import StringIO
def process(fd):
print fd.read()
contents = 'The quick brown file'
buffer = StringIO()
buffer.write(contents)
buffer.seek(0)
process(buffer) # prints "The quick brown file"
Run Code Online (Sandbox Code Playgroud)
请注意,在Python 3中,它被移动到io包中 - 您应该使用from io import StringIO而不是from StringIO import StringIO.
| 归档时间: |
|
| 查看次数: |
2685 次 |
| 最近记录: |