Tuesday, 15 September 2015

Concatenating strings inside file.write() in Python? -



Concatenating strings inside file.write() in Python? -

i trying write script in python 2.7.3 can take .csv file excel spreadsheet , convert format suitable latex table. want read file, , write info new text file, commas replaced ampersands, , double backslash appended end of each line.

example: input

a1,a2,a3 b1,b2,b3 c1,c2,c3

desired output

a1 & a2 & a3 \\ b1 & b2 & b3 \\ c1 & c2 & c3 \\

here's have right now:

old_file = open(selected_file, "r") new_file = open("texified_" + selected_file.replace("csv","txt"), "w") #creates new file format texified_selected_file.txt line in old_file: new_file.write(line.replace(",", " & ") + r" \\") new_file.close() old_file.close()

right replaces commas ampersand doesn't add together double backslash. thought because backslash has special meaning, when making raw string still doesn't work. add together end of final line, however.

actual output

a1 & a2 & a3 b1 & b2 & b3 c1 & c2 & c3 \\

i'm not sure whats wrong code (or input data), i'd similar (probably less verbose):

for line in old_file: line = line.strip() # remove newline/whitespace begin , end of line line = line.split(',') # comma-separated values line = " & ".join(line) # create ampersand-separated values line += r" \\" # add together latex line break line += "\n" # add together file line break new_file.write(line)

or way:

import jinja2 # define latex template template_str = r""" \documentclass{article} \begin{document} \begin{table} \centering \begin{tabular}{ccc} %{ line in table %} %{{line[0]%}} & %{{line[1]%}} & %{{line[2]%}} \\ %{ endfor %} \end{tabular} \end{table} \end{document} """ # initialize rendering engine renderer = jinja2.environment( block_start_string = '%{', block_end_string = '%}', variable_start_string = '%{{', variable_end_string = '%}}' ) template = renderer.from_string(template_str) # bring info array shape lines = [line.strip().split(',') line in old_file] # generate tex source code open("test.tex", 'w+') f: f.write(template.render(table=lines))

also have @ these resources:

python csv-module reading csv files jinja2 template rendering http://tex.stackexchange.com/a/40728/10704 great example

python file concatenation

No comments:

Post a Comment