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

时间:2017-01-25 21:16:00

标签: python file

源代码:

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)

问题: 为什么blury文本出现在foo.txt文件中以及我如何在文件中写出确切的文本?

enter image description here 预期输出:

\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

enter image description here

谢谢你的建议!

5 个答案:

答案 0 :(得分:4)

\t表示文字中的tab,因此您必须使用\\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)

答案 1 :(得分:1)

问题出在字符串行table_start_value中。你应该把它写成如下:

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"

即。为每个乳胶命令添加“\”。

答案 2 :(得分:1)

许多以\开头的字符组合在python中都很特殊。这样做是为了取消输出文件:

with open( inf,'w') as fwri:
    replaced_string = table_start_value.replace("\b", "\\b").replace("\t", "\\t")
    fwri.writelines(replaced_string)

答案 3 :(得分:1)

您的问题是反斜杠字符:\

在python中,反斜杠(几乎)总是会影响紧随其后的下一个字符,从而改变该字符的含义。当您使用字符串\n并且看不到文字反斜杠后跟文字“n”时,您可以看到这一点 - 而是看到换行符。这是因为反斜杠改变了“n”的含义而成为换行符。但是“n”并不是唯一受此影响的角色。

如果要在字符串中存储文字反斜杠,则需要反斜杠反斜杠,如下所示:my_string = "Here's a SINGLE backslash: \\"

对于你希望字面意思显示的字符串中的每个反斜杠,你需要反斜杠反斜杠。

答案 4 :(得分:1)

更改您的代码,以便使用原始字符串。

table_start_value= r"\begin{tab..