简体   繁体   中英

Concatenating strings inside file.write() in Python?

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 \\

That is happening probably because there is a newline already at the end of each line in your file, and not at the end of the last line .

You can try stripping it, before appending the // , and then add the newline separately: -

import os
ls = os.linesep

for line in old_file:
    new_file.write(line.replace(",", " & ").rstrip() + r' \\ ' + ls)

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

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

Or this way:

import jinja2

# define the latex template
template_str = r"""
\documentclass{article}
\begin{document}
\begin{table}
  \centering
  \begin{tabular}{ccc}
%{ for line in table %} %{{line[0]%}} & %{{line[1]%}} & %{{line[2]%}} \\ 
%{ endfor %}
  \end{tabular}
\end{table}
\end{document}

"""

# initialize the rendering engine
renderer = jinja2.Environment(
  block_start_string = '%{',
  block_end_string = '%}',
  variable_start_string = '%{{',
  variable_end_string = '%}}'
)
template = renderer.from_string(template_str)

# bring the data array into shape
lines = [line.strip().split(',') for line in old_file]

# generate the tex source code
with open("test.tex", 'w+') as f:
  f.write(template.render(table=lines))

Also have a look at these resources:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM