无法用`\n`字符将字符串保存到文件

2024-05-19 12:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码生成一个内容为test\\nstring的文件,但我需要该文件包含test\nstring。我也找不出替换\\符号的方法。你知道吗

s = "test\nstring"
with open('test.txt', 'w') as f:
    f.write(s)

如何确保文件只包含\n而不是\\n?你知道吗


Tags: 文件方法testtxt内容aswith符号
3条回答

使用s = "test\\nstring" 我尝试了以下代码并成功了。你知道吗

s = "test\\nstring"
with open('test.txt', 'w') as f:
  f.write(s)

test.txt文件包含

    test\nstring

raw strings可能会有所帮助

s = r"test\nstring"
with open('test.txt', 'w') as f:
    f.write(s)

除了转义和原始字符串之外,您还可以使用'string_escape'对其进行编码(23):

s = "test\nstring".encode('string_escape')
with open('test.txt', 'w') as f:
    f.write(s)

相关问题 更多 >