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

火山引擎 最新活动