【问题标题】:How to write array of raw bytes to google cloud storage as binary file如何将原始字节数组作为二进制文件写入谷歌云存储
【发布时间】:2014-08-17 18:14:13
【问题描述】:

我正在制作一个 AE 应用程序,它通过算法生成一个原始二进制文件(大部分是 16 位字节和一些 32 位标头字节),然后由用户下载。我可以使用以下简单代码生成此数组并将其写入普通 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),但这根本不是我想要做的。

值得一提的是,我实际上并不需要编写文件——我只需要能够将它提供给用户,如果这有帮助的话。

【问题讨论】:

    标签: python google-app-engine google-cloud-storage binaryfiles blobstore


    【解决方案1】:

    使用array.tostring函数:

    gcs_file.write(testdata.tostring())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2011-11-28
      • 2019-12-26
      • 1970-01-01
      • 2013-06-26
      相关资源
      最近更新 更多