CSV to Markdown is trivial with Python Pandas

    Python Pandas are targeted at data science applications but they are useful for everyday data conversion. I needed to convert a wide column sheet of NFRs in a TSV to Markdown for display.

    It was easy with just 4 lines of code

    This code 
    1. Opens the delimited file, 
    2. Fills in all the empty cells with empty strings, 
    3. Writes out the .md file

    df = pd.read_csv(args.csvFile, engine="python", sep=args.sep, header=args.header)
    with open(args.mdFile, "w") as md:
        df.fillna("", inplace=True)
        df.to_markdown(buf=md, index=False)

    Usage Example

    https://github.com/freemansoft/Non-Functional-Requirements

    Complete Program w Command Line Arguments

    __doc__ = """
    This converts a delimited csv file to a markdown table using pandas.
    Run with the -h option to see arguments
    """

    import pandas as pd
    import argparse

    csvFileDefault = "NFRs.tsv"
    mdFileDefault = "NFRs.md"
    headerRowDefault = 0

    parser = argparse.ArgumentParser(description="Convert tabular data to markdown tables.")
    parser.add_argument(
        "--source",
        dest="csvFile",
        default=csvFileDefault,
        help="The delimited source file [" + csvFileDefault + "]",
    )
    parser.add_argument(
        "--dest",
        dest="mdFile",
        default=mdFileDefault,
        help="The target md file [" + mdFileDefault + "]",
    )
    parser.add_argument(
        "--sep",
        dest="sep",
        default="\t",
        help="Source column separator [tab]",
    )
    parser.add_argument(
        "--header",
        dest="header",
        default=headerRowDefault,
        help="The header row [" + str(headerRowDefault) + "]",
    )

    args = parser.parse_args()

    df = pd.read_csv(args.csvFile, engine="python", sep=args.sep, header=args.header)
    with open(args.mdFile, "w") as md:
        df.fillna("", inplace=True)
        df.to_markdown(buf=md, index=False)

    Created 2022/10

    Comments

    Popular posts from this blog

    Understanding your WSL2 RAM and swap - Changing the default 50%-25%

    Installing the RNDIS driver on Windows 11 to use USB Raspberry Pi as network attached

    DNS for Azure Point to Site (P2S) VPN - getting the internal IPs