Python 是否将UTF-16转换为UTF-8并删除BOM?

Python 是否将UTF-16转换为UTF-8并删除BOM?,python,unicode,utf-8,utf-16,Python,Unicode,Utf 8,Utf 16,我们有一位数据输入人员,他在Windows上以UTF-16编码,希望使用UTF-8并删除BOM。utf-8转换有效,但BOM仍然存在。我该如何删除这个?这就是我目前拥有的: batch_3={'src':'/Users/jt/src','dest':'/Users/jt/dest/'} batches=[batch_3] for b in batches: s_files=os.listdir(b['src']) for file_name in s_files: ff_nam

我们有一位数据输入人员,他在Windows上以UTF-16编码,希望使用UTF-8并删除BOM。utf-8转换有效,但BOM仍然存在。我该如何删除这个?这就是我目前拥有的:

batch_3={'src':'/Users/jt/src','dest':'/Users/jt/dest/'}
batches=[batch_3]

for b in batches:
  s_files=os.listdir(b['src'])
  for file_name in s_files:
    ff_name = os.path.join(b['src'], file_name)  
    if (os.path.isfile(ff_name) and ff_name.endswith('.json')):
      print ff_name
      target_file_name=os.path.join(b['dest'], file_name)
      BLOCKSIZE = 1048576
      with codecs.open(ff_name, "r", "utf-16-le") as source_file:
        with codecs.open(target_file_name, "w+", "utf-8") as target_file:
          while True:
            contents = source_file.read(BLOCKSIZE)
            if not contents:
              break
            target_file.write(contents)
如果我使用hextump-C,我会看到:

Wed Jan 11$ hexdump -C svy-m-317.json 
00000000  ef bb bf 7b 0d 0a 20 20  20 20 22 6e 61 6d 65 22  |...{..    "name"|
00000010  3a 22 53 61 76 6f 72 79  20 4d 61 6c 69 62 75 2d  |:"Savory Malibu-|
在生成的文件中。如何删除BOM表

thx

只需使用并:


str.decode
将为您删除BOM表(并推断尾数)。

这就是
UTF-16LE
UTF-16

  • UTF-16LE
    是没有BOM的little endian
  • UTF-16
    是带有BOM的大尾端或小尾端
因此,当您使用
UTF-16LE
时,BOM只是文本的一部分。改用
UTF-16
,以便自动删除BOM表。之所以存在
UTF-16LE
UTF-16BE
是因为人们可以在没有BOM的情况下携带“正确编码”的文本,这不适用于您

请注意,当您使用一种编码进行编码并使用另一种编码进行解码时会发生什么。(
UTF-16
有时会自动检测
UTF-16LE
,但并不总是如此。)

或者您可以在shell中执行此操作:

for x in * ; do iconv -f UTF-16 -t UTF-8 <"$x" | dos2unix >"$x.tmp" && mv "$x.tmp" "$x"; done
用于x英寸*;do iconv-f UTF-16-t UTF-8“$x.tmp”和mv“$x.tmp”“$x”;完成

cool-效果很好,您知道如何在read中添加crlf->lf转换功能吗?thx如果你能帮忙的话,如果你在处理大文件,这种方法(将整个文件存储在内存中两次)不是很有效。
>>> u'Hello, world'.encode('UTF-16LE')
'H\x00e\x00l\x00l\x00o\x00,\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>>> u'Hello, world'.encode('UTF-16')
'\xff\xfeH\x00e\x00l\x00l\x00o\x00,\x00 \x00w\x00o\x00r\x00l\x00d\x00'
 ^^^^^^^^ (BOM)

>>> u'Hello, world'.encode('UTF-16LE').decode('UTF-16')
u'Hello, world'
>>> u'Hello, world'.encode('UTF-16').decode('UTF-16LE')
u'\ufeffHello, world'
    ^^^^ (BOM)
for x in * ; do iconv -f UTF-16 -t UTF-8 <"$x" | dos2unix >"$x.tmp" && mv "$x.tmp" "$x"; done