[英]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. 我正在使用Python将一些纯文本处理成LaTeX,因此我需要能够将\\begin{enumerate}
或\\newcommand
写入文件。 When Python writes this to a file, though, it interprets \\b
and \\n
as special characters. 但是,当Python将其写入文件时,它会将\\b
和\\n
解释为特殊字符。
How do I get Python to write \\newcommand
to a file, instead of writing ewcommand
on a new line? 如何让Python将\\newcommand
写入文件,而不是在新行上编写ewcommand
?
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 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
: 这将导致b
字符之前的字面反斜杠而不是转义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
.) (我假设最后的\\n
是故意的换行符。如果没有,也可以在这里使用双重转义: \\\\n
。)
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 注意\\ begin之前的'r'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.