CSV to Markdown Converter

1.5.0 · active · verified Fri Apr 17

csv2md is a command-line tool for converting CSV files into formatted Markdown tables. As of version 1.5.0, it is actively maintained with minor releases addressing features and bug fixes roughly every few months, ensuring correct escaping and handling of various CSV structures.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both command-line and programmatic usage. It creates a temporary CSV file and then uses `csv2md` to convert it. For CLI usage, ensure `csv2md` is installed and in your system's PATH. For programmatic use, the `convert` function expects a file-like object (e.g., `io.StringIO`).

import os
import subprocess
import tempfile
import io

# 1. Create a dummy CSV file for demonstration
csv_content = """Name,Age,City
Alice,30,New York
Bob,24,London
Charlie,22,"San Francisco|CA""" # Includes a pipe for testing escaping

csv_file_path = None
try:
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".csv", encoding="utf-8") as temp_csv_file:
        csv_file_path = temp_csv_file.name
        temp_csv_file.write(csv_content)
        temp_csv_file.flush() # Ensure content is written to disk

    print(f"--- CLI Usage (requires csv2md installed): {csv_file_path} ---")
    # This will only work if csv2md is installed and in PATH
    try:
        # Check if csv2md command is available
        subprocess.run(["csv2md", "--version"], capture_output=True, check=True)
        cmd_output = subprocess.run(
            ["csv2md", "--", csv_file_path], # Use -- to separate options from filename
            capture_output=True, text=True, check=True, encoding="utf-8"
        )
        print(cmd_output.stdout.strip())
    except FileNotFoundError:
        print("Skipping CLI example: 'csv2md' command not found. Please 'pip install csv2md'.")
    except subprocess.CalledProcessError as e:
        print(f"CLI Error: {e.stderr.strip()}")
        print(f"Output: {e.stdout.strip()}")


    print("\n--- Programmatic Usage (importing convert function) ---")
    try:
        from csv2md import convert
        # The 'convert' function expects a file-like object.
        input_stream = io.StringIO(csv_content)
        markdown_output = convert(input_stream)
        print(markdown_output.strip())
    except ImportError:
        print("Error: 'csv2md' library not found. Please 'pip install csv2md'.")
    except Exception as e:
        print(f"Programmatic Error: {e}")

finally:
    if csv_file_path and os.path.exists(csv_file_path):
        os.remove(csv_file_path)
        print(f"\nCleaned up temporary CSV: {csv_file_path}")

view raw JSON →