简体   繁体   中英

How do you write special characters (“\n”,“\b”,…) to a file in Python?

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.]<newline>

(I assume that the \\n at the end is an intentional newline. If not, use double-escaping here as well: \\\\n .)

You just need to double the backslash: \\\\n , \\\\b . This will escape the backslash. You can also put the r prefix in front of your string: r'\\begin' . As detailed here , this will prevent substitutions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM