Created
October 17, 2019 18:25
-
-
Save MineRobber9000/c22759e144e6bbd2741e4c2a69929de5 to your computer and use it in GitHub Desktop.
CSV to Markdown table generator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv,sys | |
assert len(sys.argv) in (2,3),"Usage: csv2md.py <input_file> [output_file]" | |
# assumes top row is table headers | |
with open(sys.argv[1]) as f: rows = list(csv.reader(f)) | |
max_row_length = max(*[len(r) for r in rows]) | |
for row in rows: | |
while len(row)<max_row_length: | |
row.append("") | |
max_col_length = dict() | |
for i in range(max_row_length): | |
max_col_length[i]=max(*[len(r[i]) for r in rows]) | |
def format_row(row): | |
parts = [] | |
for col in max_col_length: | |
parts.append(row[col].ljust(max_col_length[col])) | |
return "|{}|".format("|".join(parts)) | |
def format_sep(): | |
parts = [] | |
for col in max_col_length: | |
parts.append("-"*(max_col_length[col])) | |
return "|{}|".format("|".join(parts)) | |
lines = [format_row(rows[0]),format_sep()] | |
for row in rows[1:]: | |
lines.append(format_row(row)) | |
if len(sys.argv)==3: | |
with open(sys.argv[2],"w") as f: | |
f.write("\n".join(lines)+"\n") | |
else: | |
try: | |
print("\n".join(lines)) | |
except BrokenPipeError: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment