You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中向文件写入换行符转义序列而非实际换行?

How to Write Literal \n to a File Instead of a Newline in Python

Got it, I totally get what you're trying to do here! The problem is that when you use '\n' in your string, Python automatically interprets that backslash as an escape character, so it writes an actual newline to the file instead of the literal \n text you want.

Luckily, there are a couple of simple fixes for this:

  • Use a raw string
    Prefix your string with r to tell Python to treat all characters as literal, including backslashes. This is the cleanest approach for most cases:

    f.write(r"output.write(str(fib(int(line))) + '\n')")
    

    When you use a raw string, \n won't be converted to a newline—instead, the exact sequence \n will be written to your target file.

  • Double-escape the backslash
    If you prefer not to use raw strings, you can escape the backslash itself by adding a second backslash. This tells Python to treat the second backslash as a literal character:

    f.write("output.write(str(fib(int(line))) + '\\n')")
    

    Here, \\n gets parsed as the literal \n when written to the file.

  • Encode with unicode_escape (for complex cases)
    If you're dealing with a string that has multiple escape characters and want to convert all of them to literals at once, you can use string encoding:

    content = "output.write(str(fib(int(line))) + '\n')"
    f.write(content.encode('unicode_escape').decode())
    

    This method converts all escape sequences in the string to their literal representations, which is handy if you have more than just \n to handle.

After using any of these methods, when you open the target Python file, you'll see the exact line you want:
output.write(str(fib(int(line))) + '\n')

内容的提问来源于stack exchange,提问作者mattbeiswenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:47:39