您如何在Python文件中写入特殊字符("\ n","\ b",...)? [英] How do you write special characters ("\n","\b",...) to a file in Python?
问题描述
我正在使用Python将一些纯文本处理到LaTeX中,因此我需要能够将\begin{enumerate}
或\newcommand
之类的内容写入文件.但是,当Python将其写入文件时,它将\b
和\n
解释为特殊字符.
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.
如何让Python将\newcommand
写入文件,而不是在新行上写入ewcommand
?
How do I get Python to write \newcommand
to a file, instead of writing ewcommand
on a new line?
代码是这样的...
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3,Mac OS 10.5 PPC
Python 3, Mac OS 10.5 PPC
推荐答案
一种解决方案是转义转义字符(\
).这将导致在b
字符之前的文字反斜杠,而不是转义b
:
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")
这将被写入文件
\begin{enumerate}[1.]<newline>
(我假设最后的\n
是有意的换行符.如果不是,请在此处也使用双转义符:\\n
.)
(I assume that the \n
at the end is an intentional newline. If not, use double-escaping here as well: \\n
.)
这篇关于您如何在Python文件中写入特殊字符("\ n","\ b",...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!