假设文本文件与html在同一目录下,名为01.txt,提供上述方法的完整代码
时间: 2023-06-14 18:06:02 浏览: 65
以下是一个简单的 Python 代码,用于读取并显示文本文件的内容:
```python
# 导入模块
import os
# 打开文件
with open('01.txt', 'r') as file:
# 读取文件内容
content = file.read()
# 输出文件内容
print(content)
```
如果你想要将文本文件的内容显示在一个 HTML 页面中,可以使用 Flask 框架来实现。以下是一个简单的 Flask 应用程序代码片段:
```python
# 导入模块
from flask import Flask, render_template
# 创建 Flask 应用程序对象
app = Flask(__name__)
# 定义路由
@app.route('/')
def index():
# 打开文件
with open('01.txt', 'r') as file:
# 读取文件内容
content = file.read()
# 渲染模板并返回
return render_template('index.html', content=content)
# 运行应用程序
if __name__ == '__main__':
app.run()
```
在这个例子中,我们使用了 Flask 的 `render_template` 函数来渲染一个名为 `index.html` 的模板。这个模板中包含了一个用于显示文件内容的占位符,我们可以在渲染模板时将文件内容作为参数传递给它。以下是 `index.html` 的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>显示文本文件内容</title>
</head>
<body>
<h1>文本文件内容:</h1>
<pre>{{ content }}</pre>
</body>
</html>
```
在这个模板中,我们使用了 `<pre>` 标签来显示文件内容,这可以保留文本中的格式和空格。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)