You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML页面显示TXT文件内容?Flask开发技术求助

解决方案

你的代码已经完成了将文件内容传递给模板的关键步骤,只是还没在页面上把内容渲染出来。下面是具体的修正和实现步骤:

1. 优化app.py的文件读取逻辑

首先把文件读取的代码改成更安全的写法,避免文件未关闭的问题:

from flask import Flask, render_template, request, jsonify
import os
import sqlite3 as sql


app = Flask(__name__)


DATABASE_FILE = "database.db"
DEFAULT_BUGGY_ID = "1"
BUGGY_RACE_SERVER_URL = "https://rhul.buggyrace.net"

# 用with语句自动管理文件资源,读完自动关闭
with open("costs.txt", "r") as file1:
    # 如果你想读取文件全部内容用read(),只读第一行就保留readline()
    line_content = file1.read()


@app.route('/')
def home():
    # 把读取到的内容通过变量传给模板,变量名建议统一小写,避免大小写混淆
    return render_template('index.html', server_url=BUGGY_RACE_SERVER_URL, cost_content=line_content)

2. 在index.html中展示文件内容

在页面的合适位置添加模板变量渲染代码,比如在现有段落之后:

<h1>
    My buggy editor
</h1>

<div class="spacer">
    <a href="/new" class="button">Make buggy</a>
    <a href="/buggy" class="button">Show buggy</a>
    <a href="/json" class="button">Get buggy JSON</a>
</div>

<p>
    Use this editor to specify a racing buggy. The editor saves it in its
    little database and generates JSON data for the buggy. This is the data you
    need to supply when you log into the
    <strong><a href="{{ server_url }}">race server</a></strong>
    and enter your buggy into the next race.
</p>
<p>
    Remember that if your data is not accepted by the race server, your buggy
    will be disqualified from that race... so make sure you program your editor
    correctly.
</p>

<!-- 新增:展示costs.txt的内容 -->
<div class="cost-info">
    <h2>成本数据</h2>
    <!-- 用<pre>标签可以保留文件里的换行和空格格式 -->
    <pre>{{ cost_content }}</pre>
</div>

{% endblock %}

关键注意点

  • 模板里的变量名必须和render_template传递的参数名完全一致(大小写敏感),比如上面用的cost_content,两边要统一。
  • 如果你的costs.txt是多行内容,用<pre>标签包裹能保留原文件的排版,否则浏览器会把多行内容合并成一行显示。
  • 用with open读取文件是Python的标准写法,能避免忘记关闭文件导致的资源浪费问题。

内容的提问来源于stack exchange,提问作者EpicGaia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:15:05