如何在 Python 中向文件写入特殊字符(“\n”、“\b”、...)?
我正在使用 Python 将一些纯文本处理为 LaTeX,因此我需要能够将 \begin{enumerate}
或 \newcommand
之类的内容写入文件。然而,当 Python 将其写入文件时,它将 \b
和 \n
解释为特殊字符。
如何让 Python 将 \newcommand
写入文件,而不是在新行上写入 ewcommand
?
代码是这样的......
with open(fileout,'w',encoding='utf-8') as fout:
fout.write("\begin{enumerate}[1.]\n")
Python 3,Mac OS 10.5 PPC
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种解决方案是转义转义字符 (
\
)。这将导致在b
字符之前出现一个文字反斜杠,而不是转义b
:这将被写入文件
(我假设
\n 末尾是有意的换行符。如果不是,也请在此处使用双重转义:
\\n
。)One solution is to escape the escape character (
\
). This will result in a literal backslash before theb
character instead of escapingb
:This will be written to the file as
(I assume that the
\n
at the end is an intentional newline. If not, use double-escaping here as well:\\n
.)您只需要加倍反斜杠:
\\n
、\\b
。这将逃脱反斜杠。您还可以将r
前缀放在字符串前面:r'\begin'
。如此处所述,这将阻止替换。You just need to double the backslash:
\\n
,\\b
. This will escape the backslash. You can also put ther
prefix in front of your string:r'\begin'
. As detailed here, this will prevent substitutions.您还可以使用原始字符串:
注意 \begin 之前的 'r'
You can also use raw strings:
Note the 'r' before \begin