我正在尝试使用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'
关于为什么它找不到文件有什么建议吗?在
指定文件路径时,请尝试使用
os
模块。我猜你在本地主机上运行时使用的是windows pc?在确保您是从服务器的目录运行服务器。因此,如果您有如下所示的结构,就不能简单地打开终端并键入
server/__init__.py
,因为您在主目录(/home/username/
)中。你需要cd
到server
,然后运行./__init__.py
或者,如果您想从其他地方运行它,运行open the file from
os.path.abspath(os.path.dirname(__file__)) + '/temp.txt')
(用python3.5.2测试)有关
os.path
,请参阅python文档。在相关问题 更多 >
编程相关推荐