python实现不同编码的字符的转换

作者: admin 分类: python 发布时间: 2017-03-29 06:40
import sys

def filter( srcFile, encode, trgFile ):
	error = True

	while error:
		try:
			fs = open( srcFile, encoding = encode )
			content = fs.read()
			fs.close()

			error = False
			print( 'Success!' )
		except UnicodeDecodeError as ude:
			pos1, pos2 = ude.args[2], ude.args[3]
			fs = open( srcFile, 'rb' )
			content = fs.read()
			fs.close()

			content = content[:pos1] + content[pos2+1:]

			ofs = open( srcFile, 'wb' )
			ofs.write( content )
			ofs.close()

		except:
			print( 'Other error happened!' )
			break

if __name__ == '__main__':
	if len(sys.argv) < 4:
		print( 'Usage:' )
		print( sys.argv[0] + ' input-file input-encoding output-file' )
	else:
		filter( sys.argv[1], sys.argv[2], sys.argv[3] )

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注