【问题标题】:Save string to file without converting newlines using Python将字符串保存到文件而不使用 Python 转换换行符
【发布时间】:2020-11-06 12:06:08
【问题描述】:

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

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

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

hello "
" world

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

hello "\n" world

【问题讨论】:

标签: python python-3.x file newline


【解决方案1】:

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

text = 'hello "\\n" world'

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

text = r'hello "\n" world'

输出


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

'hello "\n" world'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2022-12-02
    • 1970-01-01
    • 2021-12-16
    • 2011-04-27
    相关资源
    最近更新 更多