【Python脚本】文件夹下所有文件转码GBK

本文主要讲解一个Python函数,用于在指定文件夹中自动转换所有文件的UTF-8编码至GBK编码,适合处理编码转换问题。
摘要由CSDN通过智能技术生成
# -*- 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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nonoas

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值