文件以utf-8格式打开到内存中
>>> f.read().encode('utf-8') b"201407703020 906825525 201407703022 Fanfan0618 egxefxbcx9a xe7x94xb1xe4xbax8exe5x86x85xe7xbdxaexe5x87xbdxe6x95xb0 open() xe6x89x93xe5xbcx80xe6x96x87xe4xbbxb6xe6x97xb6xefxbcx8cread() xe8xafxbbxe5x8fx96xe7x9ax84xe6x98xaf strxefxbcx8cxe8xafxbbxe5x8fx96xe5x90x8exe9x9cx80xe8xa6x81xe4xbdxbfxe7x94xa8xe6xadxa3xe7xa1xaexe7x9ax84xe7xbcx96xe7xa0x81xe6xa0xbcxe5xbcx8fxe8xbfx9bxe8xa1x8c decode()xe3x80x82write() xe5x86x99xe5x85xa5xe6x97xb6xefxbcx8cxe5xa6x82xe6x9ex9cxe5x8fx82xe6x95xb0xe6x98xaf Unicodexefxbcx8cxe5x88x99xe9x9cx80xe8xa6x81xe4xbdxbfxe7x94xa8xe4xbdxa0xe5xb8x8cxe6x9cx9bxe5x86x99xe5x85xa5xe7x9ax84xe7xbcx96xe7xa0x81xe8xbfx9bxe8xa1x8c encode()xefxbcx8cxe5xa6x82xe6x9ex9cxe6x98xafxe5x85xb6xe4xbbx96xe7xbcx96xe7xa0x81xe6xa0xbcxe5xbcx8fxe7x9ax84 strxefxbcx8cxe5x88x99xe9x9cx80xe8xa6x81xe5x85x88xe7x94xa8xe8xafxa5 str xe7x9ax84xe7xbcx96xe7xa0x81xe8xbfx9bxe8xa1x8c decode()xefxbcx8cxe8xbdxacxe6x88x90 Unicode xe5x90x8exe5x86x8dxe4xbdxbfxe7x94xa8xe5x86x99xe5x85xa5xe7x9ax84xe7xbcx96xe7xa0x81xe8xbfx9bxe8xa1x8c encode()xe3x80x82xe5xa6x82xe6x9ex9cxe7x9bxb4xe6x8exa5xe5xb0x86 Unicode xe4xbdx9cxe4xb8xbaxe5x8fx82xe6x95xb0xe4xbcxa0xe5x85xa5 write() xefxbcx8cpython xe5xb0x86xe5x85x88xe4xbdxbfxe7x94xa8xe6xbax90xe4xbbxa3xe7xa0x81xe6x96x87xe4xbbxb6xe5xa3xb0xe6x98x8exe7x9ax84xe5xadx97xe7xacxa6xe7xbcx96xe7xa0x81xe8xbfx9bxe8xa1x8cxe7xbcx96xe7xa0x81xe7x84xb6xe5x90x8exe5x86x99xe5x85xa5xe3x80x82 # coding: UTF-8 fp1 = open('test.txt', 'r') info1 = fp1.read() # xe5xb7xb2xe7x9fxa5xe6x98xaf GBK xe7xbcx96xe7xa0x81xefxbcx8cxe8xa7xa3xe7xa0x81xe6x88x90 Unicode tmp = info1.decode('GBK') 201513704089 19930818 201413703005 19930512 wwu8 eec8 eeh8 eer8 eew8 iih8 ykk8 ull8"
>>> f=open('g:chinese_and_english.txt',encoding='gbk') >>> f.read() "201407703020 906825525 201407703022 Fanfan0618 eg: 由于内置函数 open() 打开文件时,rea d() 读取的是 str,读取后需要使用正确的编码格式进行 decode()。write() 写入时,如果参数是 Unicode, 则需要使用你希望写入的编码进行 encode(),如果是其他编码格式的 str,则需要先用该 str 的编码进行 de code(),转成 Unicode 后再使用写入的编码进行 encode()。如果直接将 Unicode 作为参数传入 write() ,p ython 将先使用源代码文件声明的字符编码进行编码然后写入。 # coding: UTF-8 fp1 = open('test.tx t', 'r') info1 = fp1.read() # 已知是 GBK 编码,解码成 Unicode tmp = info1.decode('GBK') 201 513704089 19930818 201413703005 19930512 wwu8 eec8 eeh8 eer8 eew8 iih8 ykk8 ull8"
在方法里面用encoding/decoding,作为方法使用 encode/decode
>>> f=open('g:chinese_and_english.txt','r') >>> f.read() "201407703020 906825525 201407703022 Fanfan0618 eg: 由于内置函数 open() 打开文件时,rea d() 读取的是 str,读取后需要使用正确的编码格式进行 decode()。write() 写入时,如果参数是 Unicode, 则需要使用你希望写入的编码进行 encode(),如果是其他编码格式的 str,则需要先用该 str 的编码进行 de code(),转成 Unicode 后再使用写入的编码进行 encode()。如果直接将 Unicode 作为参数传入 write() ,p ython 将先使用源代码文件声明的字符编码进行编码然后写入。 # coding: UTF-8 fp1 = open('test.tx t', 'r') info1 = fp1.read() # 已知是 GBK 编码,解码成 Unicode tmp = info1.decode('GBK') 201 513704089 19930818 201413703005 19930512 wwu8 eec8 eeh8 eer8 eew8 iih8 ykk8 ull8"
dd