[英]Fix newlines when writing UTF-8 to Text file in python
我對此很不知所措。 我需要在文本文件中寫一些漢字。 以下方法有效,但是換行符被剝離,因此生成的文件只是一個超長字符串。
我嘗試插入我所知道的所有已知unicode換行符,但一無所獲。 任何幫助是極大的贊賞。 這是代碼段:
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
如果使用python 2,則使用u“ \\ n”附加換行符,並將內部unicode格式編碼為utf,當您將其寫入文件時: file_object.write((n+u"\\n").encode("utf"))
確保循環內的n
為unicode
類型。
我遇到了同樣的問題,並且效果相同(機智的目的和全部)。 就我而言,這不是編碼問題,而是需要用'\\ r \\ n'替換每個'\\ n',這可以更好地理解換行和回車之間的區別,以及Windows編輯器的事實通常需要\\ r \\ n換行符: 12747722
最簡單的方法是使用marc_a所說的“ \\ r \\ n”組合。
因此,您的代碼應如下所示:
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"\r\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.