如何在Flask中打开.txt文件?

2024-06-17 09:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python的Flask框架构建一个网站。在

我在Linux Ubuntu服务器上,有Apache2。在

在我的网站上,每当有人输入URL "/Elv_1.html",我想打开一个.txt文件,获取一些值并使用pygal创建一个图形。这是我的代码:

@app.route('/river_1.html')
def riv_1():
    try:
        document = open('temp.txt','r')

        temp_list = []
        for n in document:
            n = n.rstrip('\n')
            n = int(n)
            temp_list.append(n)

        document.close()

        graf = pygal.Line(title=u'Tempt last 24h')
        graf.x_labels = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
        graf.add('Temp', temp_list)
        graf = graf.render_data_uri()

        return render_template('river_1.html', graf=graf)
    except Exception, e:
        return str(e)

if __name__ == '__main__':
    app.run(debug=True)

文件'temp.txt'__init__.py文件位于同一目录中。__init__.py是代码来自的Flask应用程序。在

当我在我的计算机上使用localhost运行服务器时,它可以正常工作。但是,当我将此文件上载到Linux服务器并尝试输入特定的URL时,会显示以下错误:

[Error 2] No such file or directory: 'temp.txt'

关于为什么它找不到文件有什么建议吗?在


Tags: 文件代码服务器txtappurlflask网站
2条回答

指定文件路径时,请尝试使用os模块。我猜你在本地主机上运行时使用的是windows pc?在

import os
document_path = os.getcwd()+'temp.txt'
document = open(documnet_path, 'r')

确保您是从服务器的目录运行服务器。因此,如果您有如下所示的结构,就不能简单地打开终端并键入server/__init__.py,因为您在主目录(/home/username/)中。你需要cdserver,然后运行./__init__.py

/home/
  username/
    server/
      __init__.py
      temp.txt

或者,如果您想从其他地方运行它,运行open the file from os.path.abspath(os.path.dirname(__file__)) + '/temp.txt')(用python3.5.2测试)
有关os.path,请参阅python文档。在

相关问题 更多 >