【问题标题】:Writing to text file with python running on GAE使用在 GAE 上运行的 python 写入文本文件
【发布时间】:2015-01-06 19:22:15
【问题描述】:
我需要让我的 python 应用商店将一些文本存储在我已经在 GAE 上的 GCS 存储桶上创建的文件中。
到目前为止,我发现的所有文档都涵盖了比我的简单用例更复杂的示例,我越来越迷失方向。
我真正想做的就是在 GCS 上找到以下等效项(包括在 GCS 上复制它所需的任何可能的导入):
with open("../somedir/somefile.txt", "a") as myfile:
myfile.write("appended text")
有什么建议吗?
【问题讨论】:
标签:
python
google-app-engine
google-cloud-storage
【解决方案1】:
您不能在 GCS 中修改文件。一旦他们关闭,就是这样。要追加我会这样做:
import cloudstorage
from google.appengine.api import app_identity
bucketName = app_identity.get_default_gcs_bucket_name()
class MainPage(webapp2.RequestHandler):
def get(self):
fileName = "/" + bucketName + "/somedir/somefile.txt"
try:
with cloudstorage.open(fileName, "r") as gcsFile:
tempStorage = gcsFile.read()
tempStorage += "\n"
except:
tempStorage = ""
with cloudstorage.open(fileName, "w") as gcsFile:
gcsFile.write(tempStorage + "appended text")
with cloudstorage.open(fileName, "r") as gcsFile:
output= gcsFile.read()
self.response.out.write(output)
只是写作:
import cloudstorage
from google.appengine.api import app_identity
bucketName = app_identity.get_default_gcs_bucket_name()
fileName = "/" + bucketName + "/somedir/somefile.txt"
with cloudstorage.open(fileName, "w") as gcsFile:
gcsFile.write("text")
【解决方案2】:
我建议在 GAE 上将数据写入或附加到 /tmp/file。
如果文件已经完成并且不需要再修改,您可以将文件上传到 GCS,这可能会更高效。