Python 批量转换文件编码格式

本文介绍了一个使用Python编写的脚本,该脚本能批量地将指定目录下的.cpp和.h文件从其原始编码转换为UTF-8编码。通过检测文件当前编码并进行相应转换,确保文件内容在转换过程中不会丢失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:http://blog.youkuaiyun.com/vagerant/article/details/50350171

#!/usr/bin/python
#-*-coding:utf-8-*-

import os
import sys
import codecs
import chardet

def convert(filename, out_enc="UTF-8"):
	try:
		# codecs.open()这个方法打开的文件读取返回的将是unicode。
		content=codecs.open(filename,'r').read()
		#chardet.detect 获取编码格式
		source_encoding=chardet.detect(content)['encoding']
		if None != source_encoding:		#空的文件,返回None
			content=content.decode(source_encoding).encode(out_enc)
			codecs.open(filename,'w').write(content)
	except IOError as err:
		print("I/O error:{0}".format(err))

def explore(dir, source_encoding_list):
	for root,dirs,files in os.walk(dir):
		for file in files:
			#os.path.splitext(path)  分割路径,返回路径名和文件扩展名的元组
			if os.path.splitext(file)[1] in source_encoding_list:
				path=os.path.join(root,file)
				convert(path)

def main():
	explore(os.getcwd(), [".cpp", ".h"])

if __name__=="__main__":
	main()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值