Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Flask中打开.txt文件?_Python_Flask - Fatal编程技术网

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

Python 如何在Flask中打开.txt文件?,python,flask,Python,Flask,我正在尝试使用用于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 = []

我正在尝试使用用于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'
\uuuu init\uuuuu.py
文件位于同一目录中
\uuuu init\uuuu.py
是代码来自的Flask应用程序

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

[错误2]没有这样的文件或目录:“temp.txt”


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

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

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

确保您正在从服务器的目录运行服务器。因此,如果您具有如下所示的这种结构,您不能简单地打开终端并键入
服务器/uuu init\uuuu.py
,因为您位于主目录(
/home/username/
)。您需要
cd
server
并在那里运行
/\uuuu init\uuuu.py

/home/
  username/
    server/
      __init__.py
      temp.txt
或者,如果您想从其他地方运行它,请从
os.path.abspath(os.path.dirname(_file__))+'/temp.txt')
(使用python 3.5.2测试)

请参阅python文档了解
os.path

服务器上是否也存在该文件?也就是说,您是否也将
temp.txt
上传到服务器,而不仅仅是Python程序?该文件似乎与flask文件不在同一目录中。看看这是否是问题所在。这些问题通常是由于不正确的名称或不正确的路径而导致的。当您在本地运行应用程序时,它们被搁置在一旁,但在服务器上,您可以使用
wsgi server
,(如果您不这样做,您应该这样做!),python路径之间有一点不同,您应该更改为文件指定路径的方式。是的,文件将上载到服务器。my init.py与temp.txt位于同一文件夹中