Skip to content

Instantly share code, notes, and snippets.

@GrayXu
Last active March 26, 2021 10:15
Show Gist options
  • Save GrayXu/212ed3f8c610c2086df0011fcc457281 to your computer and use it in GitHub Desktop.
Save GrayXu/212ed3f8c610c2086df0011fcc457281 to your computer and use it in GitHub Desktop.
convert markdown table to csv
# warning: catch dirty corner case, but will not handle it
with open("2020Mar.md") as f:
data = f.readlines()
lengths = []
ll = []
for line in data:
items = line.split("|")[1:-1]
lengths.append(len(items))
for j in range(len(items)):
items[j] = items[j].strip()
ll.append(items)
for i in range(len(lengths)-1):
if lengths[i] != lengths[i+1]:
print("dirty!")
break
if len(ll)!=len(lengths) or len(ll[0])!=lengths[0]:
print("dirty!")
output = ""
for i in range(len(ll)):
if i == 1:
continue
else:
for j in range(len(ll[i])):
ll[i][j] = "\"" + str(ll[i][j]) + "\""
output += ",".join(ll[i])+"\n"
with open("output.csv", "w") as f:
f.write(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment