【问题标题】:Removing all BOMs from file with multiple BOMs从具有多个 BOM 的文件中删除所有 BOM
【发布时间】:2016-06-10 14:41:58
【问题描述】:

我有一个文本文件,其中包含以字节顺序标记开头的多行。将 encoding='utf-8-sig' 传递给 open 将删除文件开头的 BOM,但保留所有后续 BOM。有没有比这更正确的方法来删除这些:

import codecs

filepath = 'foo.txt'
bom_len = len(codecs.BOM_UTF8)

def remove_bom(s):
    s = str.encode(s)

    if codecs.BOM_UTF8 in s:
        s = s[bom_len:]

    return s.decode()

try:
    with open(filepath, encoding='utf-8-sig') as file_object:
        for line in file_object:
            line = line.rstrip()
            line = remove_bom(line)
            if line != '':
                print([line[0]])
except FileNotFoundError:
    print('No file found at ' + filepath)

【问题讨论】:

  • 将文件读取为二进制字符串,计算有多少个 bom,然后从字符串的开头删除那么多字节 * 3。
  • 我可能会误解:这会在文件开头返回多个 BOM all?这个文件到处都是 BOM。

标签: python byte-order-mark


【解决方案1】:

我也有类似的问题。 这对我有帮助:

import codecs
with open(path, "rb") as infile:
    bytecontent = infile.read()
bytecontent = bytecontent.replace(codecs.BOM_UTF8, b"")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2016-01-04
    • 2015-11-18
    • 2021-09-15
    • 2011-01-28
    • 2012-04-01
    相关资源
    最近更新 更多