欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > python 复制一个项目,修改编码方式

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

2025/2/9 12:07:37 来源:https://blog.csdn.net/waterHBO/article/details/140578704  浏览:    关键词: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 encodingtry: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 encodingtry: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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com