python 复制一个项目,修改编码方式

问题

阅读一些 C/C++ 项目的代码,发现有些项目是用 GBK 编码,中文注释显示为乱码。看起来很不方便。

做法:

这里把整个项目,都复制一份,转为 UTF-8 编码。

输入: 原始项目的文件夹路径
输出: 转为 UTF-8 编码的项目文件夹路径

另外

我试了 chardet ,但是检测结果很不准确,导致各种报错。所以干脆不用了。 直接默认原始项目都是 gbk 编码的。
而且我只修改 .c, .cpp, .h 这3种文件。其他不变。

import os
import shutil
# import chardet

"""目的:

阅读一些 C/C++ 项目的代码,发现大多数都是用 GBK 编码,中文注释显示为乱码。
看起来很不方便。

这里把整个项目,都复制一份,转为 UTF-8 编码。

用法:
输入: 原始项目的文件夹路径
输出: 转为 UTF-8 编码的项目文件夹路径

"""
def convert_encoding(file_path, target_encoding='utf-8'):
    # Read the file with GBK encoding
    try:
        with open(file_path, 'r', encoding='gbk', errors='ignore') as f:
            content = f.read()
    except Exception as e:
        print(f"Error reading file {file_path} with GBK encoding: {e}")
        return

    # Write the content with the target encoding
    try:
        with open(file_path, 'w', encoding=target_encoding, errors='ignore') as f:
            f.write(content)
    except Exception as e:
        print(f"Error writing file {file_path} with encoding {target_encoding}: {e}")

def copy_and_convert_files(src, dst):
    if not os.path.exists(dst):
        os.makedirs(dst)

    for root, dirs, files in os.walk(src):
        relative_path = os.path.relpath(root, src)
        dest_dir = os.path.join(dst, relative_path)
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)

        for file in files:
            src_file_path = os.path.join(root, file)
            dest_file_path = os.path.join(dest_dir, file)

            if file.endswith(('.c', '.cpp', '.h')):
                shutil.copy2(src_file_path, dest_file_path)
                convert_encoding(dest_file_path)
            else:
                shutil.copy2(src_file_path, dest_file_path)

# 示例例子
src = r'C:\Users\Administrator\Videos\NoteGuiApp'
dst = r'C:\Users\Administrator\Videos\NoteGuiApp-new'
copy_and_convert_files(src, dst)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值