-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_bom.py
66 lines (55 loc) · 2.02 KB
/
add_bom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# coding: utf-8
"""
@Createtime: 2025/04/07 12:00
@Updatetime: 2025/04/07 12:00
@Author: s1g0day
@Description: 为目录下所有CSV文件添加BOM头
"""
import os
import sys
def has_bom(file_path):
"""检查文件是否包含UTF-8 BOM头"""
try:
with open(file_path, 'rb') as f:
return f.read(3) == b'\xef\xbb\xbf'
except IOError as e:
print(f"无法读取文件 {file_path}: {e}")
return False
def add_bom_to_csv(directory):
"""为目录下所有CSV文件添加BOM头"""
modified_files = 0
skipped_files = 0
error_files = 0
for root, dirs, files in os.walk(directory):
for file in files:
if file.lower().endswith('.csv'):
file_path = os.path.join(root, file)
if has_bom(file_path):
print(f"跳过已包含BOM的文件: {file_path}")
skipped_files += 1
continue
try:
# 读取原始内容
with open(file_path, 'rb') as f:
content = f.read()
# 添加BOM头并写入新内容
with open(file_path, 'wb') as f:
f.write(b'\xef\xbb\xbf' + content)
print(f"已添加BOM头: {file_path}")
modified_files += 1
except Exception as e:
print(f"处理文件失败 {file_path}: {e}")
error_files += 1
print("\n处理完成:")
print(f"修改文件: {modified_files}")
print(f"跳过文件: {skipped_files}")
print(f"失败文件: {error_files}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("使用方法: python add_bom.py <目录路径>")
sys.exit(1)
target_dir = sys.argv[1]
if not os.path.isdir(target_dir):
print(f"错误: {target_dir} 不是有效目录")
sys.exit(1)
add_bom_to_csv(target_dir)