怎么用python(for循环)将csv文件转为html表格
时间: 2023-12-06 11:05:17 浏览: 106
可以使用Python的csv和html模块来实现将csv文件转为html表格的功能。具体步骤如下:
1. 读取csv文件并将数据存储在一个二维列表中。
```python
import csv
with open('data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
data = [row for row in csv_reader]
```
2. 将数据转换为html表格格式。
```python
html = '<table>\n'
for row in data:
html += '<tr>\n'
for col in row:
html += f'<td>{col}</td>\n'
html += '</tr>\n'
html += '</table>'
```
3. 将生成的html字符串保存到一个html文件中。
```python
with open('table.html', 'w') as html_file:
html_file.write(html)
```
完整代码如下:
```python
import csv
with open('data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
data = [row for row in csv_reader]
html = '<table>\n'
for row in data:
html += '<tr>\n'
for col in row:
html += f'<td>{col}</td>\n'
html += '</tr>\n'
html += '</table>'
with open('table.html', 'w') as html_file:
html_file.write(html)
```
这样就可以将csv文件转为html表格了。
阅读全文