Python版批量检测并删除BOM的脚本[bak]


找到了个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()

Python版本的相比PHP版的要简洁多了{真不愧是:人生苦短,我用Python}
主要体现在:
使用os.walk()实现递归遍历目录中的文件;
列表操作的快速方便。

,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注