如何在Python中向文件写入换行符转义序列而非实际换行?
\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 withrto 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,
\nwon't be converted to a newline—instead, the exact sequence\nwill 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,
\\ngets parsed as the literal\nwhen 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
\nto 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




