Skip to main content
 首页 » 编程设计

python之在 Python 中将 str 数据转换为文件对象

2025年05月04日11java哥

我正在将视频发布到 Google Cloud Buckets,签名的 PUT url 可以解决问题。但是,如果文件大小大于 10MB,它将无法工作,因此我找到了一个允许我执行此操作的开源软件,但它使用的是类似对象的文件。

def read_in_chunks(file_object, chunk_size=65536): 
while True: 
    data = file_object.read(chunk_size) 
    if not data: 
        break 
    yield data 
 
def main(file, url): 
content_name = str(file) 
content_path = os.path.abspath(file) 
content_size = os.stat(content_path).st_size 
 
print content_name, content_path, content_size 
 
f = open(content_path) 
 
index = 0 
offset = 0 
headers = {} 
 
for chunk in read_in_chunks(f): 
    offset = index + len(chunk) 
    headers['Content-Type'] = 'application/octet-stream' 
    headers['Content-length'] = content_size 
    headers['Content-Range'] = 'bytes %s-%s/%s' % (index, offset, content_size) 
    index = offset 
    try: 
        r = requests.put(url, data=chunk, headers=headers) 
        print "r: %s, Content-Range: %s" % (r, headers['Content-Range']) 
    except Exception, e: 
        print e 

我上传视频的方式是传入 json 格式的数据。

class GetData(webapp2.RequestHandler): 
def post(self): 
    data = self.request.get('file') 

然后我所做的就是一个 request.put(url, data=data)。这工作无缝。

如何将 Python 识别为 str 的数据转换为类似对象的文件?

请您参考如下方法:

所谓的“类文件”对象在大多数情况下只是一个实现 Python 缓冲区接口(interface)的对象;也就是说,具有 read、write、seek 等方法。

缓冲区接口(interface)工具的标准库模块称为io .您正在寻找 io.StringIO或 io.BytesIO ,这取决于你拥有的数据类型——如果它是一个 unicode 编码的字符串,你应该使用 io.StringIO,但你可能正在使用原始字节流(例如在图像中文件)而不仅仅是文本,所以 io.BytesIO 就是您要查找的内容。在处理文件时,这与对 unicode 文件执行 open(path, 'r') 和对原始处理执行 open(path, 'rb') 的区别相同字节数。

这两个类都将类文件对象的数据作为第一个参数,因此您只需:

f = io.BytesIO(b'test data') 

在此之后,f 将成为一个像文件一样工作的对象,除了它是将数据保存在内存中而不是磁盘上。