[英]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.