Skip to main content
 首页 » 编程设计

python之在包含 python 关键字的文件中写入行文本

2025年05月04日16JeffreyZhao

源代码:

table_start_value="\begin{table}[ht] \n\begin{center} \n\begin{tabular}{|p{2cm}|p{7cm}|p{2cm}|} \n\hline \n\multicolumn{1}{|c|}{\textbf{ID}}  \& {\textbf{Title:}}  & \multicolumn{1}{c|}{\textbf{Priority}}\\ \n\hline\n" 
 
def write_line(inf): 
    with open( inf,'w') as fwri: 
             fwri.writelines(table_start_value) 
 
file_src="foo.txt" 
write_line(file_src) 

问题: 为什么 foo.txt 文件中出现模糊文本以及如何在文件中写入准确的文本?

预期输出:

\begin{table}[ht] 
\begin{center} 
\begin{tabular}{|p{2cm}|p{7cm}|p{2cm}|} 
\hline 
\multicolumn{1}{|c|}{\textbf{ID}}  & {\textbf{Title:}}  & \multicolumn{1}{c|}{\textbf{Priority}}\\ 
\hline 

谢谢你的建议!

请您参考如下方法:

\t 表示文本中的制表符,因此您必须使用\\t。还有其他特殊字符,如 \n、\r、\b 等。您必须使用 \\如果您知道文件中的确切文本,请使用此字符。

您还可以使用 r 前缀,但使用三重 """ 并且不使用 \n 然后您不必使用 \\

table_start_value = r"""\begin{table}[ht] 
\begin{center} 
\begin{tabular}{|p{2cm}|p{7cm}|p{2cm}|} 
\hline 
\multicolumn{1}{|c|}{\textbf{ID}} & {\textbf{Title:}} & \multicolumn{1}{c|}{\textbf{Priority}}\\ 
\hline 
""" 
 
def write_line(inf): 
    with open( inf,'w') as fwri: 
             fwri.writelines(table_start_value) 
 
file_src="foo.txt" 
write_line(file_src)