简体   繁体   English

如何在Python中向文件中编写特殊字符(“\\ n”,“\\ b”,...)?

[英]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 just need to double the backslash: \\\\n , \\\\b . 你只需要加倍反斜杠: \\\\n\\\\b This will escape the backslash. 这将逃避反斜杠。 You can also put the r prefix in front of your string: r'\\begin' . 您还可以将r前缀放在字符串前面: 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 注意\\ begin之前的'r'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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