python utf8 bom_Python批量去除UTF8的Bom标签详解

本文介绍了一个Python脚本trimbom.py,用于批量删除指定文件夹中UTF8格式文件的BOM头。脚本首先定义了RemoveBom类,通过os模块遍历指定路径下的所有文件,如果文件扩展名在指定列表中,就打开文件检查前三个字节是否为BOM标识,如果是则移除并保存。最后,通过命令行参数运行脚本,可以指定要处理的文件夹和扩展名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

trimbom.py

#!/usr/bin/python

#coding=utf-8

import os

import sys

import codecs

class RemoveBom:

basePath = ''

fileList = []

trimExtList = []

def showMessages(self):

print 'the Path is [',self.basePath,']'

n = ''

for ext in self.trimExtList:

n+=ext

n+=' '

print 'the Exts is [' ,n,']'

def trimFile(self,name):

file = open(name,'rb')

content = file.read(3)

if content != '\xEF\xBB\xBF':

return False

content = file.read()

file.close()

file = open(name,'wb')

file.write(content)

file.close

print 'convert ',name,' finish'

return True

def getFileList(self,path):

if not path:

return False

for root,dirs,files in os.walk(path):

for filename in files:

if filename.split('.')[-1] in self.trimExtList:

filepath=os.path.join(root,filename)

self.trimFile(filepath)

#print filepath

def run(self,argv):

self.basePath = os.path.normpath(argv[1])

if len(argv) < 3:

self.trimExtList.append('java')

else:

for i in range(len(argv)-2):

self.trimExtList.append(argv[2+i])

self.showMessages()

self.getFileList(argv[1])

if __name__ == '__main__':

if len(sys.argv) < 2:

print 'USEAGE:python %s dirName [ext eg:java php cpp]' % __file__

sys.exit(0)

tObj = RemoveBom()

tObj.run(sys.argv)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值