#!/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