【发布时间】:2020-04-19 17:17:33
【问题描述】:
我在下面有旧代码,它使用 IO 库压缩文件并将其作为 json 存储到 S3 中(因此文件不会保存在本地)。我在转换这种相同的方法(即使用 IO 库作为缓冲区)以创建 .txt 文件并推送到 S3 并稍后检索时遇到问题。我也知道如何创建 txt 文件并推送到 s3,但不知道如何在此过程中使用 IO。
我希望存储在文本值中的值只是一个字符串值为“test”的变量
目标:使用 IO 库并将字符串变量作为文本文件保存到 S3 中,并能够再次将其拉下。
x = 'test'
inmemory = io.BytesIO()
with gzip.GzipFile(fileobj=inmemory, mode='wb') as fh:
with io.TextIOWrapper(fh, encoding='utf-8',errors='replace') as wrapper:
wrapper.write(json.dumps(x, ensure_ascii=False,indent=2))
inmemory.seek(0)
s3_resource.Object(s3bucket, s3path + '.json.gz').upload_fileobj(inmemory)
inmemory.close()
还有任何人都喜欢的关于 IO 库和写入文件的特定文档,因为实际文档( f = io.StringIO("some initial text data") ect..https://docs.python.org/3/library/io.html ) 在我目前的水平上,这并没有给我足够的帮助。
【问题讨论】:
标签: python amazon-web-services amazon-s3