遍历子文件编码格式互换(UTF-8与GB2312)
在日常开发中,我们经常会遇到需要将文件的编码格式从一种转换为另一种的情况,特别是在不同的操作系统和编辑器之间共享代码文件时。本篇文章将介绍一个Python脚本,用于遍历指定文件夹下的所有.c
和.h
文件,实现编码格式的互换,即从UTF-8转换为GB2312,或者从GB2312转换为UTF-8,并且还能清除文件中的空行。
使用场景
- 当项目中的代码文件需要从一种编码格式转换为另一种编码格式时,特别是在协作开发或文件共享时。
- 当代码文件中存在大量空行,需要一键清除时。
代码功能
- 遍历指定文件夹下的所有
.c
和.h
文件。
- 将文件的编码格式从源编码格式转换为目标编码格式。
- 清除文件中的空行,保持代码整洁。
代码思路
- 导入必要的库:
os
用于文件操作,chardet
用于检测文件编码。
- 编写
convert_encoding
函数,接受文件路径、源编码格式和目标编码格式作为参数,实现编码格式转换。
- 编写
convert_files_in_folder
函数,遍历指定文件夹下的文件,调用convert_encoding
实现编码转换。
- 编写
cleanup_file
函数,用于清除文件中的空行。
- 编写
cleanup_files_in_folder
函数,遍历指定文件夹下的文件,调用cleanup_file
进行空行清除。
- 在主程序中,指定目标文件夹路径、源编码格式和目标编码格式,分别调用
convert_files_in_folder
和cleanup_files_in_folder
函数。
示例图片
源代码
import os
import chardet
# 函数:convert_encoding
# 参数:file_path - 文件路径
# source_encoding - 源编码格式
# target_encoding - 目标编码格式
# 用途:将指定文件的编码从源编码格式转换为目标编码格式
def convert_encoding(file_path, source_encoding, target_encoding):
# 打开文件以二进制只读模式读取文件内容
with open(file_path, 'rb') as f:
content = f.read()
# 使用 chardet 检测文件内容的编码格式
detected_encoding = chardet.detect(content)['encoding']
# 如果检测到的编码格式为 None,将使用 source_encoding 作为默认编码
if detected_encoding is None:
detected_encoding = source_encoding
# 如果检测到的编码与目标编码相同,直接返回
if detected_encoding == target_encoding:
return
# 将文件内容按照检测到的编码解码为字符串
content = content.decode(detected_encoding)
# 打开文件以目标编码格式写入文件内容
with open(file_path, 'w', encoding=target_encoding) as f:
f.write(content)
# 函数:convert_files_in_folder
# 参数:folder_path - 文件夹路径
# source_encoding - 源编码格式
# target_encoding - 目标编码格式
# 用途:遍历指定文件夹下的所有 .c 和 .h 文件,并将其编码格式转换为目标编码格式
def convert_files_in_folder(folder_path, source_encoding, target_encoding):
# 遍历指定文件夹及其子文件夹中的所有文件
for root, dirs, files in os.walk(folder_path):
for file in files:
# 如果文件以 .c 或 .h 结尾,则执行编码转换
if file.endswith(('.c', '.h')):
file_path = os.path.join(root, file)
# 调用 convert_encoding 函数进行编码转换
convert_encoding(file_path, source_encoding, target_encoding)
print(f"Converted: {file_path}")
# 函数:cleanup_file
# 参数:file_path - 文件路径
# 用途:清理文件中的空行
def cleanup_file(file_path):
with open(file_path, 'rb') as f:
content = f.read()
detected_encoding = chardet.detect(content)['encoding']
if detected_encoding is None:
detected_encoding = 'utf-8'
content = content.decode(detected_encoding, errors='replace')
lines = content.splitlines()
cleaned_lines = []
for line in lines:
if line.strip(): # 如果不是空白行
cleaned_lines.append(line)
# 确保最后一行是空行
if cleaned_lines and cleaned_lines[-1]:
cleaned_lines.append('') # 添加一个空行
cleaned_content = '\n'.join(cleaned_lines)
with open(file_path, 'w', encoding=detected_encoding, newline='') as f:
f.write(cleaned_content)
# 函数:cleanup_files_in_folder
# 参数:folder_path - 文件夹路径
# 用途:遍历指定文件夹下的所有 .c 和 .h 文件,并清理文件中的空行
def cleanup_files_in_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(('.c', '.h')):
file_path = os.path.join(root, file)
cleanup_file(file_path)
print(f"Cleaned: {file_path}")
if __name__ == "__main__":
target_folder_convert = r"D:\学习\PythonCode\User"
source_encoding_convert = "utf-8"
target_encoding_convert = "gb2312"
convert_files_in_folder(target_folder_convert, source_encoding_convert, target_encoding_convert)
print("编码转换完成。")
cleanup_files_in_folder(target_folder_convert)
print("空行删除完成。")