写入文件时,Python处理换行符和制表符 [英] Python handling newline and tab characters when writing to file

查看:879
本文介绍了写入文件时,Python处理换行符和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个源文件中的一些文本(包括\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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆