简体   繁体   English

如何将 CSV 文件中的数据作为文本读取并打印到 HTML 文件中

[英]How To Read and Print Data from CSV file into HTML File as Text

I've been trying to read data from.csv file and print the data as text/number into HTML file.我一直在尝试从.csv 文件中读取数据,并将数据作为文本/数字打印到 HTML 文件中。 Like the below example:像下面的例子:

CSV 文件中的数据如下所示

Now, I want to print in HTML like this:现在,我想像这样在 HTML 中打印:

Current age of Mr. abc is 30 Years. abc 先生目前的年龄是30岁。 The bold & Italic text/numbers will be coming from the csv file and as soon as the csv file updated, the data in HTML will also update.粗体和斜体文本/数字将来自 csv 文件,一旦 csv 文件更新,HTML 中的数据也将更新。 Both the csv and HTML file will be in same local folder. csv 和 HTML 文件都将位于同一本地文件夹中。

The usual approach is to use Python's built in CSV reader to correctly parse each row into a list of values.通常的方法是使用 Python 内置的 CSV 阅读器将每一行正确解析为值列表。 The can be done as follows:可以按如下方式完成:

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")

For your sample CSV data, this would produce the following HTML output:对于您的示例 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>

An alternative approach would be to parse each line yourself, this could be done as follows:另一种方法是自己解析每一行,可以按如下方式完成:

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")
   

This though would not work if your single name column contained commas.如果您的单个名称列包含逗号,这将不起作用。 eg "John, Smith" (which is valid in CSV files, the quotes are used to ignore the commas inside)例如"John, Smith" (在 CSV 文件中有效,引号用于忽略里面的逗号)

Your link data file is not a valid link.您的链接数据文件不是有效链接。 I'll still provide you a sample implementation that you can adapt to your case:我仍然会为您提供一个示例实现,您可以根据自己的情况进行调整:

sameple.csv同样的。csv

Name, Age
ABC, 30
...

Have a separate script in same folder to create html based on your csv在同一文件夹中有一个单独的脚本来根据您的 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)

The link to the CSV data is not valid, so it is difficult to say, but in general: CSV数据的链接无效,所以很难说,但总的来说:

  • read the CSV file and split the line into specific variables (see how to read a file, how to split the css, and assign into variables)读取 CSV 文件并将该行拆分为特定变量(请参阅如何读取文件,如何拆分 css,并分配给变量)
  • the you can use the variables in HTML strings, you can use Jinja templates, but I believe that formatting the strings manually will do just fine.您可以使用 HTML 字符串中的变量,您可以使用 Jinja 模板,但我相信手动格式化字符串就可以了。

So for example if the data file is data.csv and looks like this:例如,如果数据文件是data.csv并且看起来像这样:

John:30
Emily:40
Carla:25

you can read it using the with open routine:您可以使用with open例程阅读它:

with open('data.csv', 'r') as datafile:
    data = datafile.readlines()

Now you have all the data in one list of lines, so you can iterate over the list and parse the data:现在您将所有数据都放在一个行列表中,因此您可以遍历列表并解析数据:

newdata = []
for line in data:
    newdata.append(line.rstrip().split(':'))

Now you should have all the couplets in the newdata list and you can use it as you wish.现在您应该拥有newdata列表中的所有对联,您可以随意使用它。 For instance to print out the HTML table, you could do:例如打印 HTML 表,你可以这样做:

print('<table>')
for couple in newdata:
    print(f"<tr><td>{couple[0]}</td><td>{couple[1]}</td></tr>")
print('</table>')

This will print out HTML code for the table.这将打印出表格的 HTML 代码。 To be able to control the looks of some elements by CSS, you need to use a tag like div or span with some classes, like this:为了能够通过 CSS 控制某些元素的外观,您需要将divspan之类的标签与某些类一起使用,如下所示:

for couple in newdata:
    print(f"The age of <div class="name">{couple[0]}</div> is <div class="age">{couple[1]}</div>.")

As already said, when the data is parsed, you can use whatever technique do produce the HTML - manual, Jinja templates, ... to save out the HTML file.如前所述,当数据被解析时,您可以使用任何技术生成 HTML - 手册、Jinja 模板……来保存 HTML 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM