Python 文件UTF-8编码去Bom

976 阅读1分钟

使用python修改utf8-bom编码的文件格式为utf-8(去bom)

import os
from os import path   
def removeBom(file):
    '''移除UTF-8文件的BOM字节'''
    BOM = b'\xef\xbb\xbf'
    existBom = lambda s: True if s == BOM else False
    #print("处理文件->",file)
    f = open(file, 'rb')
    if existBom(f.read(3)):
        fbody = f.read()
        with open(file, 'wb') as f:
            f.write(fbody)
        print("处理文件->",file)
    f.close()
 
 
if __name__ == '__main__':
    curDir = os.getcwd()
    print("cur dir =" ,curDir)
    for root, dirs, files in os.walk(curDir):
        for file in files:
            if file.find(".lua") != -1:
                removeBom(os.path.join(root, file))