使用 BOM 写入 UTF-16-LE 文本文件
Writing to UTF-16-LE text file with BOM
我已经阅读了一些关于 Python 写入文本文件的帖子,但我找不到解决我的问题的方法。简而言之。
要求:将由 thorn 字符(u00FE;和围绕文本值)和 pilcrow 字符(u00B6;在每列之后)分隔的值写入具有 BOM (FF FE) 的 UTF-16LE 文本文件。
问题:写入的文本文件在我没有编写脚本的每一列之间都有空白。此外,它没有在 UltraEdit 中正确显示。仅显示第一个值 ("mom")。我欢迎任何见解或建议。
脚本(经过简化以方便排错;实际脚本使用第三方API获取值列表):
import os
import codecs
import shutil
import sys
import codecs
first = u''
textdel = u'\u00FE'.encode('utf_16_le') #thorn
fielddel = u'\u00B6'.encode('utf_16_le') #pilcrow
list1 = ['mom', 'dad', 'son']
num = len(list1) #pretend this is from the metadata profile
f = codecs.open('c:/myFile.txt', 'w', 'utf_16_le')
f.write(u'\uFEFF')
for item in list1:
mytext2 = u''
i = 0
i = i + 1
mytext2 = mytext2 + item + textdel
if i < (num - 1):
mytext2 = mytext2 + fielddel
f.write(mytext2 + u'\n')
f.close()
您正在对字符串进行双重编码。您已经以 UTF-16-LE 格式打开了文件,因此不要对 textdel
和 fielddel
字符串进行编码。它们将在写入时与写入文件的每一行一起进行编码。
或者换句话说,textdel = u'\u00FE'
将 textdel
设置为 "thorn" 字符,而 textdel = u'\u00FE'.encode('utf-16-le')
将 textdel
设置为该字符的特定序列化形式,根据该编解码器的 bytes 序列;它不再是 个字符 :
的序列
textdel = u'\u00FE'
len(textdel) # -> 1
type(textdel) # -> unicode
len(textdel.encode('utf-16-le')) # -> 2
type(textdel.encode('utf-16-le')) # -> str
我已经阅读了一些关于 Python 写入文本文件的帖子,但我找不到解决我的问题的方法。简而言之。
要求:将由 thorn 字符(u00FE;和围绕文本值)和 pilcrow 字符(u00B6;在每列之后)分隔的值写入具有 BOM (FF FE) 的 UTF-16LE 文本文件。
问题:写入的文本文件在我没有编写脚本的每一列之间都有空白。此外,它没有在 UltraEdit 中正确显示。仅显示第一个值 ("mom")。我欢迎任何见解或建议。
脚本(经过简化以方便排错;实际脚本使用第三方API获取值列表):
import os
import codecs
import shutil
import sys
import codecs
first = u''
textdel = u'\u00FE'.encode('utf_16_le') #thorn
fielddel = u'\u00B6'.encode('utf_16_le') #pilcrow
list1 = ['mom', 'dad', 'son']
num = len(list1) #pretend this is from the metadata profile
f = codecs.open('c:/myFile.txt', 'w', 'utf_16_le')
f.write(u'\uFEFF')
for item in list1:
mytext2 = u''
i = 0
i = i + 1
mytext2 = mytext2 + item + textdel
if i < (num - 1):
mytext2 = mytext2 + fielddel
f.write(mytext2 + u'\n')
f.close()
您正在对字符串进行双重编码。您已经以 UTF-16-LE 格式打开了文件,因此不要对 textdel
和 fielddel
字符串进行编码。它们将在写入时与写入文件的每一行一起进行编码。
或者换句话说,textdel = u'\u00FE'
将 textdel
设置为 "thorn" 字符,而 textdel = u'\u00FE'.encode('utf-16-le')
将 textdel
设置为该字符的特定序列化形式,根据该编解码器的 bytes 序列;它不再是 个字符 :
textdel = u'\u00FE'
len(textdel) # -> 1
type(textdel) # -> unicode
len(textdel.encode('utf-16-le')) # -> 2
type(textdel.encode('utf-16-le')) # -> str