python 读取 csv数据输入网页表格
时间: 2023-11-01 17:13:12 浏览: 163
要将 CSV 数据读取到网页表格中,你需要用到 HTML 和 Python 读取 CSV 文件的相关知识。
下面是一个简单的示例代码,它使用 Flask 框架将 CSV 数据读取到网页表格中:
```python
from flask import Flask, render_template
import csv
app = Flask(__name__)
@app.route('/')
def index():
data = []
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
data.append(row)
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run(debug=True)
```
在上面的代码中,我们使用 Flask 框架创建了一个 Web 应用程序,当用户访问网站的首页时,将读取 CSV 文件中的数据,并将其传递给 `index.html` 模板进行渲染。
下面是 `index.html` 模板的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>CSV Data</title>
</head>
<body>
<table>
{% for row in data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
```
在上面的代码中,我们使用了 Jinja2 模板引擎将 CSV 数据渲染成了一个 HTML 表格。在模板中,我们使用了 `for` 循环遍历 CSV 数据,将其渲染成了一个表格。
你需要确保在运行示例代码时,确保在同一目录下存在名为 `data.csv` 和 `index.html` 的文件。
阅读全文
相关推荐
















