Reputation: 309
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
Upvotes: 5
Views: 25252
Reputation: 31498
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.]<newline>
(I assume that the \n
at the end is an intentional newline. If not, use double-escaping here as well: \\n
.)
Upvotes: 12
Reputation: 13776
You can also use raw strings:
with open(fileout,'w',encoding='utf-8') as fout:
fout.write(r"\begin{enumerate}[1.]\n")
Note the 'r' before \begin
Upvotes: 4