2013-08-17 94 views
2

我有一个函数的期望一个文件对象,简化的示例:您可以将文件内容转换为文件对象吗?

def process(fd): 
    print fd.read() 

这通常被称为:

fd = open('myfile', mode='r') 
process(fd) 

我不能改变该功能,并且我已经有内容内存中的文件。有没有什么办法convert文件内容到一个文件对象,而不将其写入磁盘,所以我可以做这样的事情:用StringIO

contents = 'The quick brown file' 
fd = convert(contents) # ?? 
process(fd) 

回答

6

你可以这样做:

该模块实现类文件类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" 

注意的是Python 3,它被转移到io包 - 你应该使用from io import StringIO而不是from StringIO import StringIO

+1

您可能想要注意的是,在Python 3中,它已被移入'io'模块中。 – icktoofay

+0

@icktoofay好点,谢谢 – alecxe

相关问题