我正在使用 Python 将一些纯文本处理成 LaTeX,所以我需要能够将 \begin{enumerate}
或 \newcommand
之类的东西写到文件。但是,当 Python 将其写入文件时,它会将 \b
和 \n
解释为特殊字符。
如何让 Python 将 \newcommand
写入文件,而不是在新行上写入 ewcommand
?
代码是这样的……
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3、Mac OS 10.5 PPC
最佳答案
一种解决方案是转义转义字符 (\
)。这将导致在 b
字符之前出现文字反斜杠,而不是转义 b
:
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\\begin{enumerate}[1.]\n")
这将被写入文件中
\begin{enumerate}[1.]<newline>
(我假设末尾的 \n
是有意换行。如果不是,请在此处使用双重转义:\\n
。)
关于python - 如何将特殊字符 ("\n","\b",...) 写入 Python 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4245709/