Categories

# CSV to Tex Table – Python

This is a very simple and basic script that will change a CSV file to a tex table. It is so simple that it may not be able to handle complex text…and may actually have many bugs…but still useful.

# converts a csv file to a tex table.
from re import sub

# you neet to cd to the actual directory and enter the
# csv name with extension.
str_csv_file_dir = raw_input('name of csv file: ')
str_tex_file = raw_input('name of output file: ')

with open(str_csv_file_dir,'r') as file_r_csv:
list_csv_rows = str_csv_contents.split('\n')

# tex document format
str_tex_start = '\documentclass{article}\n\\begin{document}\n'
str_tex_end = '\end{document}'

# table format
# get number of columns
list_tex_tab_start = ['\\begin{center}\n\t\\begin{tabular}{']
list_row_comps = list_csv_rows[0].split(',')
for int_col in range(0,len(list_row_comps)):
list_tex_tab_start.append('l ')
list_tex_tab_start.append('}\n')
str_tex_tab_start = ''.join(list_tex_tab_start)

str_tex_tab_end = '\t\\end{tabular}\n\\end{center}\n'

# change the csv rows to tex rows
list_tex_rows = []
for str_csv_row in list_csv_rows:
if len(str_csv_row) > 1:
str_tex_r1 = sub(',','\t&\t',str_csv_row)
list_tex_rows.append('\t\t'+str_tex_r1+'\t\\\\\n')
str_tex_rows = ''.join(list_tex_rows)

# build output
list_full_tex_output = [str_tex_start,
str_tex_tab_start,
str_tex_rows,
str_tex_tab_end,
str_tex_end]

# create output file
file_output = open(str_tex_file+'.tex','w')
file_output.write(''.join(list_full_tex_output))
file_output.close()


## Example

The sample.csv looks like this

,hello,world
1,this,is
2,a,nice
3,simple,sample


So we cd to the directory where the sample.csv file is, and we run the above python script.

we should then get this

name of csv file:


so we write the full name of the file with extension and press enter, then we get a second message where we write the name of the output file without the extension and press enter again.

name of csv file: sample.csv
name of output file: sample_output


Finally, the script created the tex file with this

% sample_output.tex
\documentclass{article}
\begin{document}
\begin{center}
\begin{tabular}{l l l }
&	hello	&	world	\\
1	&	this	&	is	\\
2	&	a	&	nice	\\
3	&	simple	&	sample	\\
\end{tabular}
\end{center}
\end{document}


and if we make the pdf file, the table should look like this