按UTF-8 w/ BOM读入文件,再用UTF-8存储。如果源文件不是UTF-8 w/ BOM或UTF-8 w/o BOM编码,会抛出异常并打印文件全路径,但程序不会终止。
import os
def convert(d):
for f in os.listdir(d):
full = os.path.join(d, f)
if os.path.isfile(full):
try:
s = open(full, mode='r', encoding='utf-8-sig').read()
open(full, mode='w', encoding='utf-8').write(s)
except Exception as e:
print(f'ERROR: Non UTF-8 encoded file found: {full}')
if os.path.isdir(full):
convert(full)



