![](/img/trans.png)
[英]How to read in data from a csv file and insert the data into an html file
[英]How To Read and Print Data from CSV file into HTML File as Text
通常的方法是使用 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 output:
<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>
另一种方法是自己解析每一行,可以按如下方式完成:
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 文件中有效,引号用于忽略里面的逗号)
您的链接数据文件不是有效链接。 我仍然会为您提供一个示例实现,您可以根据自己的情况进行调整:
同样的。csv
Name, Age
ABC, 30
...
在同一文件夹中有一个单独的脚本来根据您的 csv 创建 html
csv_data=open('sample.csv','r').read().split('\n')
html_body = ''
for line in csv_data:
line = line.split(',')
html_body += f'<p>Mr. {line[0]} is {line[1]} Years</p>\n'
html_output = '<html><body>\n'+html_body+'</body></html>'
with open('html_out.html', 'w') as outfile:
outfile.write(html_output)
CSV数据的链接无效,所以很难说,但总的来说:
例如,如果数据文件是data.csv
并且看起来像这样:
John:30
Emily:40
Carla:25
您可以使用with open
例程阅读它:
with open('data.csv', 'r') as datafile:
data = datafile.readlines()
现在您将所有数据都放在一个行列表中,因此您可以遍历列表并解析数据:
newdata = []
for line in data:
newdata.append(line.rstrip().split(':'))
现在您应该拥有newdata列表中的所有对联,您可以随意使用它。 例如打印 HTML 表,你可以这样做:
print('<table>')
for couple in newdata:
print(f"<tr><td>{couple[0]}</td><td>{couple[1]}</td></tr>")
print('</table>')
这将打印出表格的 HTML 代码。 为了能够通过 CSS 控制某些元素的外观,您需要将div
或span
之类的标签与某些类一起使用,如下所示:
for couple in newdata:
print(f"The age of <div class="name">{couple[0]}</div> is <div class="age">{couple[1]}</div>.")
如前所述,当数据被解析时,您可以使用任何技术生成 HTML - 手册、Jinja 模板……来保存 HTML 文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.