python删除utf8文件bom头信息

发布时间:2020-05-12编辑:脚本学堂
本文介绍了python删除bom文件头信息的方法,一个python删除bom头信息的小例子,有需要的朋友参考下。
python删除bom文件头:
复制代码 代码示例:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
def delBOM():
 file_count = 0
 bom_files  = []
 for dirpath, dirnames, filenames in os.walk('.'):
  if(len(filenames)):
   for filename in filenames:
    file_count += 1
    file = open(dirpath + "/" + filename, 'r+')
    file_contents = file.read()
    if(len(file_contents) > 3):
     if(ord(file_contents[0]) == 239 and ord(file_contents[1]) == 187 and ord(file_contents[2]) == 191):
      bom_files.append(dirpath + "/" + filename)
      file.seek(0)
      file.write(file_contents[3:])
      print bom_files[-1], "BOM found. Deleted."
    file.close()
 print file_count, "file(s) found.", len(bom_files), "file(s) have a bom. Deleted."
if __name__ == "__main__":
 delBOM()