09-01-2022, 01:21 AM
Python Convert Markdown Table to CSV
5/5 – (1 vote)
Problem
Given the following Markdown table stored in:
Python Challenge: How to convert the Markdown table to a CSV file ?
![[Image: image-97.png]](https://blog.finxter.com/wp-content/uploads/2022/08/image-97.png)
Solution
To convert a Markdown table file to a CSV file in Python, first read the Markdown table file by using the method on the opened file object , by splitting along the markdown table separator symbol . Clean up the resulting list (row-wise) and add all rows to a single list of lists. Then create a DataFrame from the list of lists and use the method to write it to a CSV file.
An example is shown in the following script that you can use for your own conversion exercise by replacing only the in-file and out-file names highlighted below:
The resulting CSV file:
Learn More
Background Tutorials: The code uses a multitude of Python features. Check out these articles to learn more about them:
5/5 – (1 vote)
Problem
Given the following Markdown table stored in
Code:
'my_file.md'Code:
| 1 | 2 | 3 | 4 | 5 |
|-------|-----|------|------|------|
| 0 | 0 | 0 | 0 | 0 |
| 5 | 4 | 3 | 2 | 1 |
| alice | bob | carl | dave | emil |
Python Challenge: How to convert the Markdown table to a CSV file Code:
'my_file.csv'![[Image: image-97.png]](https://blog.finxter.com/wp-content/uploads/2022/08/image-97.png)
Solution
To convert a Markdown table
Code:
.mdCode:
f.readlines()Code:
fCode:
'|'Code:
DataFrame.to_csv()An example is shown in the following script that you can use for your own conversion exercise by replacing only the in-file and out-file names highlighted below:
Code:
import pandas as pd # Convert the Markdown table to a list of lists
with open('my_file.md') as f: rows = [] for row in f.readlines(): # Get rid of leading and trailing '|' tmp = row[1:-2] # Split line and ignore column whitespace clean_line = [col.strip() for col in tmp.split('|')] # Append clean row data to rows variable rows.append(clean_line) # Get rid of syntactical sugar to indicate header (2nd row) rows = rows[:1] + rows[2:] print(rows)
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', index=False, header=False)The resulting CSV file
Code:
'my_file.csv'Code:
1,2,3,4,5
0,0,0,0,0
5,4,3,2,1
alice,bob,carl,dave,emil
Background Tutorials: The code uses a multitude of Python features. Check out these articles to learn more about them:
