Skip to content

Instantly share code, notes, and snippets.

@diramazioni
Last active June 22, 2023 23:48
Show Gist options
  • Save diramazioni/5ac8f2aecb21fcc148bf625c6ec808c3 to your computer and use it in GitHub Desktop.
Save diramazioni/5ac8f2aecb21fcc148bf625c6ec808c3 to your computer and use it in GitHub Desktop.
Convert a CSV table into LaTeX
def csv2latex(file_path, sep):
with open(file_path, 'r') as file:
lines = file.readlines()
# count how many column there is
col = lines[0].count(sep) + 1
empty_line = sep*int(col-1)
start = ['\\begin{table} \n','\caption{Table captions should be placed above the tables.}\label{tab1} \n']
new = start
tabular = '\\begin{tabular}{'+'|l|'*col+'}\hline \n'
new.append(tabular)
for i, line in enumerate(lines):
#print(i, line)
if empty_line in line:
line = line.replace(empty_line,"\hline")
else:
line = line.replace("_","\_")
line = line.rstrip('\n') + '\\\\\n'
new.append(line)
if i == 0:
new.append('\hline \n')
end = '''\\hline
\\end{tabular}
\\end{table}
'''
new += [l + "\n" for l in end.split("\n")]
with open(file_path, 'w') as file:
file.writelines(new)
### use your csv and separator ie '&'
file_path = 'validation.csv'
csv2latex(file_path, '&')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment