Skip to main content
 首页 » 编程设计

python之使用 StringIO 对象保存 uu.encode/uu.decode 数据

2025年05月04日7yxwkf

我想做以下事情:

import StringIO, uu 
my_data = StringIO.StringIO() # this is a file-like object 
uu.encode(in_file, my_data) 
# do stuff with my data (send over network) 
uu.decode(my_data, out_file) # here I finally write to disk 

上面的代码有效。但是,如果我将上一步实现为对象中的属性:

@property 
def content(self): 
 out = StringIO.StringIO() 
 uu.decode(self._content, out) 
 return out.getvalue() 
@content.setter 
def content(self, value): 
 self._content = StringIO.StringIO() 
 with open('value', 'rb') as stream: 
  uu.encode(stream, self._content) 

但是当我这样做时,self._content 是空的(准确地说是None)。有什么想法吗?

请您参考如下方法:

self._content 在 content.setter 方法写入后在其end 处留下“当前点”。您可能想在该方法的末尾添加 self._content.seek(0),以便接下来可以读取该伪文件的开头(从末尾开始阅读将返回“nothing more”,这是非常正确的,因为它确实从末尾开始,这可能就是让您觉得它是“空的”的原因;-)。