# -*- coding: utf-8 -*-
import os
def convert_encoding(file_path, from_encoding='utf-8', to_encoding='gbk'):
try:
with open(file_path, 'r', encoding=from_encoding) as f:
content = f.read()
with open(file_path, 'w', encoding=to_encoding) as f:
f.write(content)
print(f"Converted {file_path} from {from_encoding} to {to_encoding}")
except Exception as e:
print(f"Error converting {file_path}: {e}")
def convert_folder_encoding(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
convert_encoding(file_path)
if __name__ == '__main__':
# 调用函数来转换指定文件夹下的所有文件编码为GBK
out_path = 'E:/xx/xx'
convert_folder_encoding(out_path)
【Python脚本】文件夹下所有文件转码GBK
于 2024-03-20 12:13:54 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)