Skip to content
Advertisement

Writing HTML Entities to a File

I’m getting a UnicodeEncodeError when I run the code below. It simply loops until i = 9000, appends an html entity to a list based upon the value of i, then writes the list to a file after looping. Doe’s anyone know where I’m going wrong?

for i in range(9000):
    list.append(html.unescape("&#" + str(i) + ";"))

open("file.txt", "w").write(", ".join(list))

Advertisement

Answer

By default this open method doesn’t support unicode, so you have to set the correct encoding for that

open('file.txt', 'w', encoding='utf-8').write(", ".join(list))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement