Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write special characters ("\n","\b",...) to a file in Python?

Tags:

python

latex

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

like image 525
registrar Avatar asked Nov 28 '22 11:11

registrar


1 Answers

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.)

like image 156
jensgram Avatar answered Dec 06 '22 11:12

jensgram