在Python中如何在file.write()中连接字符串?

2 投票
2 回答
11491 浏览
提问于 2025-04-17 15:26

我正在尝试用Python 2.7.3写一个脚本,这个脚本可以读取一个Excel表格中的.csv文件,并把它转换成适合LaTeX表格的格式。也就是说,我想读取一个文件,然后把数据写入一个新的文本文件,但要把所有的逗号替换成&符号,并在每一行的末尾加上两个反斜杠。

举个例子:
输入

A1,A2,A3  
B1,B2,B3  
C1,C2,C3

期望的输出

A1 & A2 & A3 \\
B1 & B2 & B3 \\
C1 & C2 & C3 \\

这是我现在的代码:

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

现在代码能正确地把逗号替换成&符号,但没有在每一行的末尾加上两个反斜杠。我原以为这是因为反斜杠有特殊含义,但即使把它写成原始字符串,还是不行。不过,它确实在最后一行的末尾加上了。

实际输出

A1 & A2 & A3   
B1 & B2 & B3  
C1 & C2 & C3 \\

2 个回答

1

这可能是因为你文件中每一行的末尾已经有一个换行符,但最后一行的末尾没有。

你可以试着先去掉这些换行符,然后再加上//,最后再单独添加一个换行符:-

import os
ls = os.linesep

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

我不太确定你的代码(或者你的输入数据)哪里出了问题,但我可能会这样做(可能会简洁一些):

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)

或者这样做:

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

另外,可以看看这些资源:

撰写回答