使用 Python 将字符串保存到文件而不转换换行符

Save string to file without converting newlines using Python

我想使用 Python 将以下字符串保存到文件中。该字符串包括 \n 我不想将其转换为新行。这是我的代码:

text = 'hello "\n" world'
file = open("file.js", "w")
file.write(text)
file.close()

当我打开 file.js 时,我得到以下输出(这是预期的):

hello "
" world

有什么方法可以保存文件而不强制转换换行符?我想要的文件输出是:

hello "\n" world

您可以通过转义反斜杠 (\) 来实现。所以,你可以像这样转义换行符:

text = 'hello "\n" world'

您还可以使用名为 raw-strings 的东西,它会自动为您转义反斜杠。这些是以 r:

开头的字符串
text = r'hello "\n" world'

输出


写入文件时,您将得到以下内容,中间没有任何换行符:

'hello "\n" world'