I am trying to write a script in Python 2.7.3 that can take a .csv file from an Excel spreadsheet and convert it to a format suitable for a LaTeX table. So I want to read a file, and write the data to a new text file, but with any commas replaced with ampersands, and a double backslash appended to the 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 what I have right now:
old_file = open(selected_file, "r")
new_file = open("texified_" + selected_file.replace("csv","txt"), "w")
#Creates new file with format texified_selected_file.txt
for line in old_file:
new_file.write(line.replace(",", " & ") + r" \\")
new_file.close()
old_file.close()
Right now it properly replaces the commas with the ampersand but doesn’t add the double backslash. I thought this was because the backslash has special meaning, but even when making it a raw string it still doesn’t work. It does add it to the end of the final line, however.
Actual Output
A1 & A2 & A3
B1 & B2 & B3
C1 & C2 & C3 \\
I’m not sure whats wrong with your code (or with your input data), but I’d probably do it similar to this (probably less verbose):
Or this way:
Also have a look at these resources: