写入文件时,Python处理换行符和制表符 [英] Python handling newline and tab characters when writing to file
问题描述
我正在将一个源文件中的一些文本(包括\n
和\t
字符)写到一个(文本)文件中;例如:
I am writing some text (which includes \n
and \t
characters) taken from one source file onto a (text) file ; for example:
源文件(test.cpp):
source file (test.cpp):
/*
* test.cpp
*
* 2013.02.30
*
*/
取自源文件,并存储在这样的字符串变量中
is taken from the source file and stored in a string variable like so
test_str = "/*\n test.cpp\n *\n *\n *\n\t2013.02.30\n *\n */\n"
当我使用文件写入文件时
which when I write onto a file using
with open(test.cpp, 'a') as out:
print(test_str, file=out)
是用换行符和制表符转换成新行和制表符空格的(正像test.cpp
拥有它们一样)而我希望它们保持\n
和test_str
变量将它们放在第一位一样.
is being written with the newline and tab characters converted to new lines and tab spaces (exactly like test.cpp
had them) whereas I want them to remain \n
and \t
exactly like the test_str
variable holds them in the first place.
在将这些特殊字符"写入文件而不进行翻译时,是否有办法在Python中实现?
Is there a way to achieve that in Python when writing to a file these 'special characters' without them being translated?
推荐答案
您可以使用str.encode
:
with open('test.cpp', 'a') as out:
print(test_str.encode('unicode_escape').decode('utf-8'), file=out)
这将转义所有Python识别的特殊转义字符.
This'll escape all the Python recognised special escape characters.
给出您的示例:
>>> test_str = "/*\n test.cpp\n *\n *\n *\n\t2013.02.30\n *\n */\n"
>>> test_str.encode('unicode_escape')
b'/*\\n test.cpp\\n *\\n *\\n *\\n\\t2013.02.30\\n *\\n */\\n'
这篇关于写入文件时,Python处理换行符和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!