Skip to main content
 首页 » 编程设计

python之如何将原始字节数组作为二进制文件写入谷歌云存储

2025年05月04日10yxwkf

我正在制作一个 AE 应用程序,它通过算法生成原始二进制文件(主要是 16 位字节和一些 32 位 header 字节),然后由用户下载。我可以使用以下简单代码生成此数组并将其写入普通 python 中的文件:

import numpy as np 
import array as arr 
 
toy_data_to_write = arr.array('h', np.zeros(10, dtype=np.int16)) 
output_file = open('testFile.xyz', 'wb') 
toy_data_to_write.tofile(output_file) 

显然,这在 AE 中不起作用,因为不允许写入,所以我尝试在 GCS 中做类似的事情:

import cloudstorage as gcs 
 
self.response.headers['Content-Type'] = 'application/octet-stream' 
self.response.headers['Content-Disposition'] = 'attachment; filename=testFile.xyz' 
testfilename = '/' + 'xyz-app.appspot.com' + '/testfile' 
gcs_file = gcs.open(testfilename,'w',content_type='application/octet-stream') 
testdata = arr.array('h', np.zeros(10, dtype=np.int16)) 
gcs_file.write(testdata) 
gcs_file.close() 
gcs_file = gcs.open(testfilename) 
self.response.write(gcs_file.read()) 
gcs_file.close() 

这段代码给了我一个TypeError,基本上是说write()需要一个字符串,没有别的。请注意,array 模块的 .tofile() 函数不适用于 AE/GCS。

有没有办法让我写一个这样的文件?我的理解是我无法以某种方式将字符串编码为将被正确写入的原始二进制文件(不是 ASCII 或类似的东西),所以我想要的可能是不可能的? :( Blobstore 有什么不同吗?还有一个类似(听起来)的问题(here),但这根本不是我想要做的。

值得一提的是,我并不真的需要编写该文件——我只需要能够将其返回给用户(如果有帮助的话)。

请您参考如下方法:

使用 array.tostring功能:

gcs_file.write(testdata.tostring())