将带有BOM的UTF-8转换为UTF-8,在Python中没有BOM

tim*_*one 67 python byte-order-mark utf-8 utf-16

这里有两个问题.我有一组文件,通常是带有BOM的UTF-8.我想将它们(理想情况下)转换为没有BOM的UTF-8.似乎codecs.StreamRecoder(stream, encode, decode, Reader, Writer, errors)会处理这个问题.但我真的没有看到任何关于使用的好例子.这是处理这个的最佳方法吗?

source files:
Tue Jan 17$ file brh-m-157.json 
brh-m-157.json: UTF-8 Unicode (with BOM) text
Run Code Online (Sandbox Code Playgroud)

此外,如果我们能够处理不同的输入编码而不明确地知道(看到ASCII和UTF-16),那将是理想的.看起来这应该都是可行的.有没有可以将任何已知的Python编码和输出作为UTF-8而无BOM的解决方案?

从下面编辑1提出的sol'n(谢谢!)

fp = open('brh-m-157.json','rw')
s = fp.read()
u = s.decode('utf-8-sig')
s = u.encode('utf-8')
print fp.encoding  
fp.write(s)
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

IOError: [Errno 9] Bad file descriptor
Run Code Online (Sandbox Code Playgroud)

新闻快报

我在评论中被告知错误是我用模式'rw'而不是'r +'/'r + b'打开文件,所以我最终应该重新编辑我的问题并删除已解决的部分.

Mar*_*ler 105

只需使用"utf-8-sig"编解码器:

fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")
Run Code Online (Sandbox Code Playgroud)

这会给你一个unicode没有BOM 的字符串.然后你可以使用

s = u.encode("utf-8")
Run Code Online (Sandbox Code Playgroud)

重新获得正常的UTF-8编码字符串s.如果您的文件很大,那么您应该避免将它们全部读入内存.BOM只是文件开头的三个字节,因此您可以使用此代码将它们从文件中删除:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk = fp.read(BUFSIZE)
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            fp.seek(i)
            fp.write(chunk)
            i += len(chunk)
            fp.seek(BOMLEN, os.SEEK_CUR)
            chunk = fp.read(BUFSIZE)
        fp.seek(-BOMLEN, os.SEEK_CUR)
        fp.truncate()
Run Code Online (Sandbox Code Playgroud)

它打开文件,读取一个块,并将其写入文件,比它读取的位置早3个字节.该文件就地重写.更简单的解决方案是将较短的文件写入新文件,如newtover的答案.这会更简单,但在短时间内使用两倍的磁盘空间.

至于猜测编码,那么你可以从大多数到最不具体的循环编码:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            continue
    return s.decode("latin-1") # will always work
Run Code Online (Sandbox Code Playgroud)

UTF-16编码的文件不能解码为UTF-8,因此我们首先尝试使用UTF-8.如果失败,那么我们尝试使用UTF-16.最后,我们使用Latin-1 - 这将始终有效,因为所有256个字节都是Latin-1中的合法值.None在这种情况下你可能想要返回,因为它确实是一个后备,你的代码可能想要更仔细地处理它(如果可以的话).

  • 似乎得到``AttributeError:'str'对象没有属性'decode'```。所以我最终使用代码作为 ```with open(filename,encoding='utf-8-sig') as f_content:```,然后 ```doc = f_content.read()``` 它适用于我。 (2认同)

Gen*_*wen 40

在Python 3中,它非常简单:读取文件并使用utf-8编码重写它:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)
Run Code Online (Sandbox Code Playgroud)

  • 网络上有关此主题的最佳答案。只需使用 utf-8-sig。 (3认同)
  • 也适用于2.7。只需从编解码器导入即可。 (2认同)

new*_*ver 6

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)
Run Code Online (Sandbox Code Playgroud)


小智 6

configparser.ConfigParser().read(fp)我发现这个问题是因为在打开带有 UTF8 BOM 标头的文件时遇到问题。

对于那些正在寻找删除标头以便 ConfigPhaser 可以打开配置文件而不是报告以下错误的解决方案的用户 File contains no section headers,请按以下方式打开文件:

configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")
Run Code Online (Sandbox Code Playgroud)

这样就无需删除文件的 BOM 标头,从而节省大量精力。

(我知道这听起来无关,但希望这可以帮助像我一样苦苦挣扎的人。)

  • 因为我第一次使用 try - except --> 这也可以毫无问题地打开 UTF-8“非 BOM”编码文件 (2认同)

est*_*evo 5

这是我的实现,将任何类型的编码转换为没有 BOM 的 UTF-8 并用通用格式替换 windows enlines:

def utf8_converter(file_path, universal_endline=True):
    '''
    Convert any type of file to UTF-8 without BOM
    and using universal endline by default.

    Parameters
    ----------
    file_path : string, file path.
    universal_endline : boolean (True),
                        by default convert endlines to universal format.
    '''

    # Fix file path
    file_path = os.path.realpath(os.path.expanduser(file_path))

    # Read from file
    file_open = open(file_path)
    raw = file_open.read()
    file_open.close()

    # Decode
    raw = raw.decode(chardet.detect(raw)['encoding'])
    # Remove windows end line
    if universal_endline:
        raw = raw.replace('\r\n', '\n')
    # Encode to UTF-8
    raw = raw.encode('utf8')
    # Remove BOM
    if raw.startswith(codecs.BOM_UTF8):
        raw = raw.replace(codecs.BOM_UTF8, '', 1)

    # Write to file
    file_open = open(file_path, 'w')
    file_open.write(raw)
    file_open.close()
    return 0
Run Code Online (Sandbox Code Playgroud)