Skip to content
Advertisement

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. 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.

Advertisement

Answer

The usual approach is to use Python’s built in CSV reader to correctly parse each row into a list of values. 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:

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

To create one HTML per row, you would need to rearrange things a bit and also decide on a naming scheme for the output files. This adds the name to each filename:

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

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. e.g. "John, Smith" (which is valid in CSV files, the quotes are used to ignore the commas inside)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement