通常的方法是使用 Python 内置的 CSV 阅读器将每一行正确解析为值列表。可以这样做:
import csv
with open('input.csv') as f_input, open('output.html', 'w') as f_output:
csv_input = csv.reader(f_input)
header = next(csv_input) # skip the header
# Write the HTML header
f_output.write("<html>\n<body>\n")
for row in csv_input:
f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")
# Write the HTML footer
f_output.write("</body>\n</html>\n")
对于您的示例 CSV 数据,这将产生以下 HTML 输出:
<html>
<body>
Current age of Mr. abc is 20 Years.<br>
Current age of Mr. xyz is 30 Years.<br>
Current age of Mr. jkl is 40 Years.<br>
</body>
</html>
要为每行创建一个 HTML,您需要重新安排一些内容,并确定输出文件的命名方案。这会将名称添加到每个文件名:
import csv
with open('input.csv', encoding='utf-8') as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input) # skip the header
for row in csv_input:
with open(f'output_{row[0]}.html', 'w', encoding='utf-8') as f_output:
# Write the HTML header
f_output.write("<html>\n<body>\n")
f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")
# Write the HTML footer
f_output.write("</body>\n</html>\n")
另一种方法是自己解析每一行,可以按如下方式完成:
with open('input.csv') as f_input, open('output.html', 'w') as f_output:
header = next(f_input) # skip the header
# Write the HTML header
f_output.write("<html>\n<body>\n")
for line in f_input:
row = line.strip().split(',')
f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")
# Write the HTML footer
f_output.write("</body>\n</html>\n")
如果您的单个名称列包含逗号,这将不起作用。例如"John, Smith"(在CSV文件中有效,引号用来忽略里面的逗号)