Skip to content

Instantly share code, notes, and snippets.

@mtask
Last active November 23, 2023 20:57
Show Gist options
  • Save mtask/11eb3fb553738bca6dbbfd606c2d2cf5 to your computer and use it in GitHub Desktop.
Save mtask/11eb3fb553738bca6dbbfd606c2d2cf5 to your computer and use it in GitHub Desktop.
Python csv to markdown table

Convert the following csv syntax to markdown table:

```table
some,csv,data
1,2,3
```

Script csv_md_tables.py will look for "table blocks" and converts the csv content to markdown table. For example, the above content in a markdown file would be converted to this:

|some|csv|data|
|---|---|---|
|1|2|3|
some csv data
1 2 3

Script supports comma seperated CSV files and handles potential commas inside a column data if extra commas are in the last column.

import sys
def create_table(table_lines):
table = []
header = True
for line in table_lines:
line = line.replace('\n','').split(",")
if header:
n_column = len(line)
items = line[:n_column -1] + [','.join(line[n_column - 1:])]
table.append(f"|{'|'.join(items)}|")
if header:
header = False
table.append(f'{"|---" * n_column}|')
return table
def convert_tables(input_content) -> list:
#with open(input_file) as f:
content = []
in_table = False
table_lines = []
for line in input_content:
line = line.replace('\n','')
if "```table" in line:
in_table = True
continue
if in_table and line == "```" :
in_table = False
content.extend(create_table(table_lines))
table_lines = []
continue
if in_table:
table_lines.append(line)
else:
content.append(line)
return '\n'.join(content)
# Test
input_content = """
# Some header
Some text
```table
user,age,desc
mike,21,"Mike,21 years old"
bob,18,"Mike,18 years old"
```
More text
"""
print(convert_tables(input_content.split('\n')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment