简体   繁体   English

换行符被Python忽略

[英]Newline character is ignored by Python

When I'm trying to write a string b'<?xml version="1.0" encoding="utf-8"?> \\n<response list="true">\\n <audio>\\n <aid>412317542</aid>\\n ... to a new .xml file, it gets written as a single line , ignoring all \\n characters. 当我尝试编写字符串b'<?xml version="1.0" encoding="utf-8"?> \\n<response list="true">\\n <audio>\\n <aid>412317542</aid>\\n ...到一个新的.xml文件,它将被写为一行 ,而忽略所有\\n字符。

Why is it happening, and how do I get several lines ? 为什么会发生,如何获得多行

My code: 我的代码:

page = urlopen(url)
html = page.read()    # Here I get the xml data
with open('output.xml', 'w', encoding='utf-8') as f:
    f.write(str(html))

Your string looks like is bytes object , so you should use bytes.decode() , not just str() : 您的字符串看起来像是bytes对象 ,因此您应该使用bytes.decode() ,而不仅仅是str()

page = urlopen(url)
html = page.read()    # Here I get the xml data

with open('output.xml', 'w', encoding='utf-8') as f:
    f.write(html.decode(page.headers.get_content_charset()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM