Fix newlines when writing UTF-8 to text file in python

I am on my way on this. I need to write some Chinese characters in a text file. The following method works, however, newlines become stripped, so the resulting file is only one super long line.

I tried to insert every known unicode line break that I know of and nothing. Any help is appreciated. Here is a snippet:

import codecs file_object = codecs.open( 'textfile.txt', "w", "utf-8" ) xmlRaw = (data to be written to text file ) newxml = xmlRaw.split('\n') for n in newxml: file_object.write(n+(u'2424'))# where \u2424 is unicode line break 
+4
source share
1 answer

If you are using python 2, use u "\ n" to add a new line and encode the Unicode internal format to utf when you write it to a file: file_object.write((n+u"\n").encode("utf")) Make sure n is of unicode type inside your loop.

+2
source

Source: https://habr.com/ru/post/1496255/


All Articles