将gbk编码的.h文件和.cpp文件转为utf-8编码,python实现
程序员文章站
2022-03-31 19:09:19
...
注意下面代码中的dst目录在运行之前不存在,并且osp.basename(src)等于osp.basename(dst),即360SafeDemo部分。
import os.path as osp
import os
import shutil
def fun(src, dst):
basename = osp.basename(src)
head, tail = osp.split(dst)
names = os.listdir(head)
if basename in names:
pass
else:
shutil.copytree(src, dst)
for root, dirs, files in os.walk(src):
for file in files:
path = osp.join(root, file)
a, b = osp.splitext(path)
if (b == '.h' or b == '.cpp'):
new_path = path.replace(src, dst, 1)
try:
with open(path, 'r', encoding='gbk') as f:
data = f.read()
with open(new_path, 'w', encoding='utf-8') as f:
f.write(data)
except:
print(path)
if __name__ == '__main__':
src = r"F:\Qt\360SafeDemo"
dst = r"F:\python\360SafeDemo"
fun(src, dst)