python 文件读写

    最近有个项目,工程是utf-8的,最后要求打jar包打GBK的,但是如果直接使用eclipse进行转换的话,中文注释就会出现问题,为了解决这个问题,不得不写脚本批量对整个工程目录进行编码转换,转换思路是先把utf-8转换成unicode,再从unicode转换成GBK,这样的话就可以保证中文注释能够不丢失的情况下转换过来。

     文件处理的话,用python最好,python的文件处理强大且简单,不像java里面各种流和buffer那么复杂。废话不多说,上代码:

代码的功能就是将指定目录下的所有文件拷贝一份,并看针对特殊的文件进行编码转换,例如我这里讲.java .pom .xml文件进行了转换

#encoding=utf-8
#!/usr/bin/python
import os
import shutil

"""
开发过程中遇到需要将java工程从utf-8转到gbk的,直接使用eclipse转是做
不到的,于是想着开发一个脚本,遍历目录去做这件事情。

这个类的作用就是将指定目录下的所有文件(文件类型可配置)转换成指定编码格式
"""
class FilesEncodeConvetor():

	def __init__(self, folderPath, suffix):
		self.basePath = folderPath
		self.newBasePath = folderPath+'_new'
		self.suffixList = self._praseSuf(suffix)

	#按逗号分割
	def _praseSuf(self, suffix):
		return suffix.split(',')

	#初始化文件信息
	def _initFileList(self):
		#将文件列表建立起来
		self.fileList = os.listdir(self.basePath)

	def convert(self):
		print('*'*7+"begin"+'*'*7)
		print('old: ['+self.basePath+']')
		print('new: ['+self.newBasePath+']')

		self._convert_folder(self.basePath, self.newBasePath)

		return

	def _convert_folder(self, folderpath, targetfolder):

		if not os.path.exists(folderpath):
			print("某已经存在,直接返回")
			return

		self._makedir(targetfolder)
		#print("目标目录拷贝完成: "+targetfolder+'*'*9)

		for f in os.listdir(folderpath):

			#隐藏的文件不拷贝
			if f.startswith('.'):
				continue

			f_new = os.path.join(folderpath, f)
			target_f = os.path.join(targetfolder, f)
			if os.path.isdir(f_new):
				if f in self.exceptFolderList:
					continue
				self._convert_folder(f_new, target_f)

			if os.path.isfile(f_new):
				self._convert_file(f_new, target_f)

	def _convert_file(self, file_from, file_to):

		
		if not os.path.exists(file_from):
			return

		#取后缀
		f_suffix = os.path.splitext(file_from)[1]

		#后缀不在配置内的就直接进行copy,不进行编码转换
		if f_suffix not in self.suffixList:
			if not os.path.exists(file_to):
				shutil.copyfile(file_from, file_to)

		else:
			self._convert_encode_file(file_from, file_to)

		#print("拷贝文件结束"+file_to+' '+'*'*9)


	def _convert_encode_file(self, file_from, file_to):

		if os.path.exists(file_to):
			print('文件已经存在'+file_to)
			return

		try:
			in_file = open(file_from, 'r')
			out_file = open(file_to, 'wb')
			text = in_file.read()
			out_file.write(text.decode(self.encode_from).encode(self.encode_to))

		except Exception, e:
			print e
			print '拷贝目标文件失败'+file_to+'*'*9
			out_file.close()

			os.remove(file_to)
			shutil.copyfile(file_from, file_to)
			print('重新拷贝成功'+file_to+'*'*9)
		else:
			pass
		finally:
			in_file.close()
			out_file.close()
			pass

	def _makedir(self, dirpath):
		if os.path.exists(dirpath):
			return

		os.mkdir(dirpath)

	def setEncodeFromTo(self, encode_from, encode_to):
		self.encode_from = encode_from
		self.encode_to = encode_to


	def setFolderExcept(self, f_list):
		self.exceptFolderList = f_list



if __name__ == '__main__':
	folderpath = '/Users/hupeng/Downloads/temp/test/acts'
	suffix= '.pom,.xml,.java,.MF'
	convertor = FilesEncodeConvetor(folderpath, suffix)
	convertor.setEncodeFromTo('utf8', 'gb18030')

	except_folder = []
	except_folder.append('target')
	except_folder.append('logs')
	convertor.setFolderExcept(except_folder)
	convertor.convert()
	

代码如上,本人比较喜欢用python做文件处理和运维相关的,如果有问题可以直接咨询我qq623158938

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值