I've been trying to read data from .csv file and print the data as text/number into HTML file. Like the below example:
Data from CSV file looks like this
Now, I want to print in HTML like this: Current age of Mr. abc is 30 Years. 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. Both the csv and HTML file will be in same local folder.
CodePudding user response:
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
Name, Age
ABC, 30
...
Have a separate script in same folder to create html based on your csv
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)
CodePudding user response:
The link to the CSV data is not valid, so it is difficult to say, but in general:
- 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)
- 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.
So for example if the data file is data.csv and looks like this:
John:30
Emily:40
Carla:25
you can read it using the with open routine:
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. For instance to print out the HTML table, you could do:
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.
As already said, when the data is parsed, you can use whatever technique do produce the HTML - manual, Jinja templates, ... to print or save a HTML file.
