【问题标题】:GoogleAppEngine: How to read text file using python?GoogleAppEngine:如何使用 python 读取文本文件?
【发布时间】:2013-02-03 07:31:26
【问题描述】:

我的项目结构是这样的

flask-appengine-template/
                        docs/
                        licenses/
                        src/
                            application/
                                        static/
                                        templates/
                                        models.py
                                        settings.py
                                        urls.py
                                        views.py
                                        english.txt
                        libs/
                            bs4/
                         app.yaml
                         src.py

在我的views.py 中,我有一个读取文件english.txt 的函数

      for words in open('english.txt', 'r').readlines():
            stopwords.append(words.strip())

当我在 local environment 上运行此程序时,我在日志中看到错误为

(<type 'exceptions.IOError'>, IOError(13, 'file not accessible'), <traceback object at 0x10c457560>)

如何在 Google App Engine 中读取此文件?

【问题讨论】:

  • 这个问题可能相关吗? stackoverflow.com/q/2630205/1947535
  • open('english.txt','r') -> open('templates/english.txt','r')?
  • 尝试从应用程序的根目录:open('src/application/english.txt', 'r')
  • 将数据从english.txt转换为english.py(包含单词列表)并导入。

标签: python file google-app-engine


【解决方案1】:

如果english.txt只是一个单词列表,我建议将单词列表转换为python列表,这样你就可以导入它。

如果english.txt 包含更复杂的数据,请将其移至bigtable 或您的应用可用的其他数据库。

与标准 VPS 相比,AppEngine 是一个非常残缺的环境,我倾向于避免在底层操作系统上运行的功能,例如 open()

【讨论】:

  • 我尝试了您建议的方式并且效果很好,谢谢@Paulo
  • @Paulo crippled,你的意思是性能方面或 w.r.t. api支持?在读取文件系统时,不要像 jinja 这样的模板库一直这样做吗?
  • 这个答案已经很老了,有些过时了;与 VPS 相比,GAE 以前的“平台即服务”产品有一些限制(例如,只有纯 Python 库、有限的 I/O 等)。现在我认为他们允许一种混合 PaaS/IaaS 方法,您可以从 GCP 附加网络卷并在 GAE 中执行标准 I/O。
【解决方案2】:

您需要使用 os.path 来获得对文件路径的正确引用,类似于:

def read_words():
    import os.path
    folder = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(folder, 'english.txt')
    for words in open(file_path, 'r').readlines():
        stopwords.append(words.strip())

希望有帮助!

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2017-07-27
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2021-12-22
    • 2015-03-05
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多