-
Notifications
You must be signed in to change notification settings - Fork 2
/
utf8encode.py
58 lines (39 loc) · 1.29 KB
/
utf8encode.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
import chardet
from pathlib import Path
import argparse
import os
TARGET_ENCODING = "utf-8"
EXTENSIONS = ('*.c', '*.cpp', '*.h', '*.fx', '*.ini', '*.txt', '*.ani')
def predict_encoding(filename):
with open(filename, 'rb') as f:
rawdata = f.read()
return chardet.detect(rawdata)['encoding']
def change_encoding(filename):
source_encoding = predict_encoding(filename)
if source_encoding is None:
return False
print(f'{filename}: {source_encoding}')
with open(filename, 'r', encoding=source_encoding) as f:
content = f.read()
with open(filename, 'w', encoding=TARGET_ENCODING) as f:
f.write(content)
return True
def process_directory(path):
files = []
for ext in EXTENSIONS:
files.extend(Path(path).rglob(ext))
errors = []
for filename in files:
if not change_encoding(filename):
errors.append(filename)
return errors
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("path", help="root directory for a file search")
args = parser.parse_args()
path = os.path.abspath(args.path)
errors = process_directory(path)
if errors:
print("errors:")
for x in errors:
print(x)