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

2024-04-19 10:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一个在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)

如果我看到hexdump-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-|

在生成的文件中。如何删除物料清单?

泰铢


Tags: pathnamesrctargetosbatchcontentsbom
2条回答

这就是UTF-16LEUTF-16之间的区别

  • UTF-16LE是没有BOM的小endian
  • UTF-16是带有BOM的big或little endian

所以当您使用UTF-16LE时,BOM只是文本的一部分。改为使用UTF-16,这样BOM将自动删除。存在UTF-16LEUTF-16BE的原因是,人们可以随身携带“正确编码”的文本,而无需bom,这不适用于您。

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

>>> 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)

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

for x in * ; do iconv -f UTF-16 -t UTF-8 <"$x" | dos2unix >"$x.tmp" && mv "$x.tmp" "$x"; done

只需使用^{}^{}

with open(ff_name, 'rb') as source_file:
  with open(target_file_name, 'w+b') as dest_file:
    contents = source_file.read()
    dest_file.write(contents.decode('utf-16').encode('utf-8'))

str.decode将为您除去BOM(并推断endianness)。

相关问题 更多 >