【问题标题】:Why file read/write adds additional lines to the file?为什么文件读/写会在文件中添加额外的行?
【发布时间】:2014-12-16 16:31:50
【问题描述】:

我想取消转义源文件中的 unicode 字符:

source = open('source.csv', 'r')
target = open('target.csv', 'w')
target.write(source.read().decode('unicode_escape').encode('utf-8'))

但结果文件包含额外的换行符。例如,文本

u'\u0417a\u0439\u043c\u044b \u0412ce\u043c \u0436e\u043ba\u044e\u0449\u0438\u043c!\nO\u0434o\u0431\u0440e\u043d\u0438e 98%'

被替换为

u'Зaймы Вceм жeлaющим!
Oдoбрeниe 98%'

了解源文本中有换行符\n,但我想保持原样,无需实际转换为换行符。

【问题讨论】:

    标签: python file python-2.7 line-breaks


    【解决方案1】:

    你快到了:

    for line in source:
        line = line.rstrip('\n')
        line = line.decode('unicode_escape').replace(u'\n', u'\\n').encode('utf8')
        target.write(line + '\n')
    

    【讨论】:

    • 谢谢。但是现在每一行都以\n 开头,我在源文件中没有。并且再次添加了一些额外的行(试图找到有问题的行)。
    • @LA_:已修复,请参阅答案。
    • 该文件还包含 \r\n 和仅 \r 符号。我尝试用\\n 替换它们,然后用\\r\\n\\r 相应地替换它们,但它要么在每一行的末尾添加\n 符号并只返回一行(即错过所有换行符)。
    • 在解码之前进行替换可能更容易。
    • 以下效果很好 - line.replace(u'\r\n', u'\\r\\n').replace(u'\r', u'\\r').replace(u'\n', u'\\n').rstrip('\\r')。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多