Vasily
Vasily

Reputation: 2514

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.

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))

Upvotes: 0

Views: 848

Answers (1)

Remi Guan
Remi Guan

Reputation: 22282

Your string looks like is bytes object, so you should use bytes.decode(), not just 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()))

Upvotes: 2

Related Questions