python 中文编码转换

#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
newRaw = "1中"
def convert(filename):
    
    raw = open(filename,'wb').write(newRaw.encode('utf-16'))
    raw.close()

def main1():
    fileDir = ""
    for root,dirs, files in os.walk(fileDir):
        for file in files:
            convert(os.path.join(root, file))
    os.system("pause")
def newfile(filename):
    try:
        f = open(filename, 'wb')
        # print(f.write(newRaw.encode('utf-16-le')))      #中文双字节小字节序 ,英文双字节后面补00 ,windows不能正常显示 编码: 31 00 2d 4e
        # print(f.write(newRaw.encode('utf-16-be')))      #中文双字节大字节序 ,英文双字节前面补00,windows不能正常显示  编码:00 31 4e 2d
        print(f.write(newRaw.encode('utf-16')))           #中文四字节 ,英文双字节,windows可正常显示 6 unicode         编码 ff fe 31 00 2d 4e
        # print(f.write(newRaw.encode('utf-8')))          #中文三字节 ,英文单字节,windows可正常显示 6 utf-8           编码 31 e4 b8 ad
        # print(f.write(newRaw.encode('utf-8-sig')))      #windows可正常显示 7                                        编码 ef bb bf 31 e4 b8 ad
        # print(f.write(newRaw.encode('gbk')))            #中文双字节 ,英文单字节,windows可正常显示  ansi             编码 31 d6 d0

    finally:
        if f:
            f.close()
def newfile2(filename):
    with open(filename, 'w' ,encoding='utf-16') as f:
        f.write(newRaw)
def readfile(filename):
    try:
        f = open(filename, 'rb')
        data = f.read()
        # data = "中国人"
        # print(data)
        for i in data:
            print("%02x "%(i),end='')
        print("cat 2:%s"%(data[0:3]))
    finally:
        if f:
            f.close()

if __name__ == '__main__':
    newfile2("./a.txt")
    readfile("./a.txt")

#注意 open 和 with open 打开文件,一个必须 加 b,一个不能加b

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值