Python can convert CSV to an HTML table by parsing records with the csv module and escaping every cell with html.escape before assembling the markup.

That separation matters in scripts, web views, report jobs, and build pipelines. A CSV record is not necessarily a physical line, and a cell may contain a comma or a line ending, so treating each line as an array of comma-separated strings can shift every later column. The example below uses only the standard library and creates an HTML table fragment rather than a full HTML document.

convert csv to html table python
Convert CSV to HTML Table in Python: Safe Escaping

The parsing rules that prevent broken tables

Use Python's csv.reader instead of str.split(',') to define field boundaries. Validate record widths before emitting any tags, then escape the values as text. This ordering keeps parsing, data validation, and presentation separate: malformed input fails early, while characters such as < and > become entities instead of markup.

Stage Python choice Why it matters
Read open(..., newline="") Lets the CSV parser recognize record endings inside quoted fields.
Parse csv.reader(..., strict=True) Handles quoted delimiters, doubled quotes, and embedded record endings; strict mode raises an error for bad quoting.
Validate len(row) Checks every record against the first record's field count.
Escape html.escape(value, quote=True) Encodes ampersands, angle brackets, quotes, and apostrophes before tags are assembled.
Assemble thead, tbody, tr, th, and td elements Keeps column headings and data rows structurally distinct.

The reader returns cell text rather than inferred numbers or dates, and it does not trim surrounding spaces. That makes the conversion faithful, but it also leaves formatting decisions explicit. The width check rejects records with too few or too many fields, including a blank line represented as an empty record. It never guesses which field is missing or silently discards the row. Empty middle and trailing cells remain part of the record.

Run the conversion in Python

  1. Use Python 3 and save the following as csv_to_html.py. It treats the first record as headings by default, rejects uneven records, escapes every cell, and writes the table to table.html.

    import csv import html from pathlib import Path def csv_to_html_table(csv_path, html_path, has_header=True): with open(csv_path, "r", encoding="utf-8-sig", newline="") as source: rows = list(csv.reader(source, delimiter=",", quotechar='"', doublequote=True, strict=True)) if not rows or not rows[0]: raise ValueError("CSV must contain at least one record with fields.") width = len(rows[0]) if any(len(row) != width for row in rows): raise ValueError("Every record must contain the same number of fields.") parts = ["<table>"] if has_header: parts.extend(["<thead>", "<tr>"]) parts.extend(f'<th scope="col">{html.escape(value, quote=True)}</th>' for value in rows[0]) parts.extend(["</tr>", "</thead>"]) parts.append("<tbody>") body_rows = rows[1:] if has_header else rows for row in body_rows: parts.append("<tr>") parts.extend(f"<td>{html.escape(value, quote=True)}</td>" for value in row) parts.append("</tr>") parts.extend(["</tbody>", "</table>"]) Path(html_path).write_text("\n".join(parts) + "\n", encoding="utf-8") csv_to_html_table("data.csv", "table.html")

  2. Place the input file beside the script and name it data.csv. For example:

    Name,Role,City "Le, Jr.","Engineer","New York" Sam,Designer,Bristol

  3. Run python3 csv_to_html.py from that folder. On Windows, py csv_to_html.py is the corresponding Python launcher.

  4. Open table.html and compare its logical rows and columns with the source. If the first record is data rather than headings, change the final call to csv_to_html_table("data.csv", "table.html", has_header=False); every record will then become a tbody row containing td cells.

Check the generated HTML before integration

The output contains a table element, a thead section when a header is selected, and a tbody section for the records. In header mode, the first row uses th elements with scope="col", while data rows use td elements. In non-header mode, every record appears as a row of td elements inside tbody.

Check the first row, last row, row count, and column count against the source. Give special attention to quoted commas, doubled quotes, embedded line endings, empty middle cells, and empty trailing cells. If a source cell contains an ampersand or angle bracket, confirm that the generated cell contains an entity rather than a literal tag delimiter. Escaping prevents cell text from becoming markup, but the destination still needs a safe HTML insertion path and its own content security policy.

Make the fragment accessible and responsive

A syntactically valid table can still be difficult to navigate or read. The generated fragment supplies table structure, not a complete accessible design. In the destination, follow the WHATWG HTML table guidance and add the presentation and semantics required by the surrounding page.

  • Add a concise caption when the table's purpose is not immediately clear. If nearby text already provides that context, make the relationship explicit instead of adding redundant visual content.
  • Keep native table, thead, tbody, tr, th, and td elements. Use appropriate heading scope relationships, including row-header semantics when the first column labels each row.
  • Place the fragment inside a container such as div class="table-scroll" with horizontal overflow enabled. This preserves the table structure while allowing narrow screens to scroll across wide columns.
  • Test the integrated page with long values, empty cells, zoomed text, and a narrow viewport. A valid source table can still become unusable when its columns are extremely wide.
  • If the destination adds sorting, filtering, or pagination, implement those features there and test their keyboard and announcement behavior. They are not included in a converted table fragment.

Cross-check the source in the browser converter

The related CSV to HTML Table Converter is a browser-based alternative, not a Python library. It is useful when you want a copy-ready fragment directly or want to cross-check a representative CSV sample before embedding the Python result. Its input is CSV, so paste the original source rather than the generated HTML.

  1. Paste comma-delimited CSV into the converter.
  2. Choose whether the first record contains column headings.
  3. Convert the input and compare the reported row and column counts with the expected logical records.
  4. Inspect both the safe preview and the generated source.
  5. Copy the escaped table fragment after the counts and structure look correct.

Parsing, escaping, preview construction, and clipboard access stay inside the current browser tab. The preview renders cell content literally, so script, image, event-handler, or tag-like strings do not become active elements there. The copied fragment still belongs only in its intended HTML content context, and the destination application must maintain its own content security policy.

Where the browser converter is deliberately limited

The browser converter uses a narrow RFC 4180-style dialect rather than guessing a source format. Check these conditions before relying on it for a particular file.

Input condition Verified behavior
Delimiter Comma is the only delimiter. Semicolons, tabs, and pipes remain ordinary cell characters; the converter does not guess another separator.
Record endings CRLF is canonical, while standalone LF and CR are accepted as interoperability extensions. A final record ending is optional and does not create an extra row.
Quoted fields Quoted commas and record endings are accepted, and two double quotes decode to one literal quote. A quote in the middle of an unquoted field is rejected. After a closing quote, only a comma, record ending, or end of input is accepted.
Record widths Every record must contain exactly the same number of fields as the first record. Empty middle and trailing cells are retained.
Header choice With headers enabled, the first record becomes one thead row of th cells and the remaining records become tbody rows of td cells. With headers disabled, every record becomes a td row in tbody.
Cell text The converter does not trim text, infer numbers or dates, calculate formulas, merge cells, interpret comments, detect spreadsheet types, or repair malformed records. One leading U+FEFF is removed as a BOM signature; the same character elsewhere remains data.
Budgets The limits are 500,000 input characters, 10,000 total rows, 200 columns, 200,000 cells, and 5,000,000 output characters. Crossing a boundary returns an error with no partial or silently truncated table.
Output The result is a fragment, not a full document. It contains no doctype, html, head, body, caption, CSS, JavaScript, ARIA description, sorting, filtering, pagination, or responsive wrapper.

Because the dialect is comma-only, a semicolon-delimited file can validly appear as one column. Convert that source to comma-delimited CSV first or use software that explicitly supports its delimiter. Inspect the source dialect before converting a representative sample rather than expecting the converter to repair mismatched or malformed input.

Diagnose shifted columns and malformed records

Most shifted-column failures originate in parsing rather than HTML generation. Use this sequence when the output looks incorrect:

  • Confirm that the source is comma-delimited. Do not assume a tab, semicolon, or pipe file will be recognized.
  • Count logical records rather than physical lines, because a quoted record ending can make one record span multiple lines.
  • Treat a strict quoting error as a source-format problem. Do not split around the offending quote, because that can silently move data into the wrong column.
  • Treat an uneven-width error as invalid input. Padding or truncating rows would hide the mismatch and could misrepresent the dataset.
  • Separate data rendering from layout. Escaping resolves the boundary between cell text and markup; CSS and responsive behavior resolve visual overflow.

If you're weighing options, CSV to JSON for Beginners: Rows, Keys, and Strings covers this in detail.

If you're weighing options, Convert Excel to HTML: Local XLSX Table Workflow covers this in detail.