I am writing some text (which includes \n and \t characters) taken from one source file onto a (text) file ; for example:
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)
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.
Is there a way to achieve that in Python when writing to a file these 'special characters' without them being translated?
解决方案
You can use str.encode:
with open('test.cpp', 'a') as out:
print(test_str.encode('unicode_escape').decode('utf-8'), file=out)
This'll escape all the Python recognised special escape characters.
Given your example:
>>> 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'