【问题标题】:How to open a file in Google App Engine using python 3.5?如何使用 python 3.5 在 Google App Engine 中打开文件?
【发布时间】:2019-06-02 21:57:52
【问题描述】:

我可以在本地机器上使用以下行加载我的 txt 文件。

lines=open(args['train_file1'],mode='r').read().split('\n')

args 是具有训练文件目录的dict。

现在我将工作 python 版本更改为 3.5,现在我收到此错误。我不知道为什么会出现这个错误,该文件存在于该目录中。

FileNotFoundError: [Errno 2] No such file or directory: 'gs://bot_chat-227711/data/movie_lines.txt'

【问题讨论】:

    标签: python-3.x google-app-engine


    【解决方案1】:

    如果我正确理解了您的问题,您正尝试从 App Engine 中的 Cloud Storage 读取文件。

    您不能使用open 函数直接执行此操作,因为云存储中的文件位于云中的存储桶中。由于您使用的是 Python 3.5,因此您可以使用 Python Client library for GCS 来处理位于 GCS 中的文件。

    这是一个小例子,它在 App Engine 应用程序的处理程序中读取位于 Bucket 中的文件:

    from flask import Flask
    from google.cloud import storage
    
    
    app = Flask(__name__)
    
    
    @app.route('/openFile')
    def openFile():
        client = storage.Client()
        bucket = client.get_bucket('bot_chat-227711')
        blob = bucket.get_blob('data/movie_lines.txt')
        your_file_contents = blob.download_as_string()
        return your_file_contents
    
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=8080, debug=True)
    

    请注意,您需要将行 google-cloud-storage 添加到您的 requirements.txt 文件中才能导入和使用此库。

    【讨论】:

    • 由于 OP 想要对文件进行一些处理,因此最好将其加载到内存中而不是保存到磁盘。有关将 GCS 文件加载到内存中的方法,请检查:stackoverflow.com/questions/49357352/…
    • 我相信download_as_string 方法已经这样做了,因为它将 Blob 文件的内容作为字节字符串返回,而不是将其保存到本地文件中。我将编辑示例以使其更清晰。
    猜你喜欢
    • 2012-12-27
    • 2013-06-10
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多