I'm using Python to process some plain text into LaTeX, so I need to be able to write things like \begin{enumerate} or \newcommand to a file. When Python writes this to a file, though, it interprets \b and \n as special characters.
How do I get Python to write \newcommand to a file, instead of writing ewcommand on a new line?
The code is something like this ...
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3, Mac OS 10.5 PPC
解决方案
One solution is to escape the escape character (\). This will result in a literal backslash before the b character instead of escaping b:
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\\begin{enumerate}[1.]\n")
This will be written to the file as
\begin{enumerate}[1.]
(I assume that the \n at the end is an intentional newline. If not, use double-escaping here as well: \\n.)