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: ')

# read csv file
with open(str_csv_file_dir,'r') as file_r_csv:
    str_csv_contents =
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 ')
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)
str_tex_rows = ''.join(list_tex_rows)

# build output
list_full_tex_output = [str_tex_start,

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


The sample.csv looks like this


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
	\begin{tabular}{l l l }
			&	hello	&	world	\\
		1	&	this	&	is	\\
		2	&	a	&	nice	\\
		3	&	simple	&	sample	\\

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

Screen Shot 2013-06-05 at 10.34.44

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s