Python:str file,open,read,write,close,and utf8 BOM resloving

文章推薦指數: 80 %
投票人數:10人

Python:str file,open,read,write,close,and utf8 BOM resloving - utf8_decode.py. Skiptocontent Allgists BacktoGitHub Signin Signup Sign in Sign up {{message}} Instantlysharecode,notes,andsnippets. rswofxd/utf8_decode.py CreatedMay9,2012 Star 0 Fork 0 Star Code Revisions 1 Embed Whatwouldyouliketodo? Embed Embedthisgistinyourwebsite. Share Copysharablelinkforthisgist. Clonevia HTTPS ClonewithGitorcheckoutwithSVNusingtherepository’swebaddress. LearnmoreaboutcloneURLs DownloadZIP Python:strfile,open,read,write,close,andutf8BOMresloving Raw utf8_decode.py ThisfilecontainsbidirectionalUnicodetextthatmaybeinterpretedorcompileddifferentlythanwhatappearsbelow.Toreview,openthefileinaneditorthatrevealshiddenUnicodecharacters. LearnmoreaboutbidirectionalUnicodecharacters Showhiddencharacters #coding:utf-8 #PYTHONIOENCODING=utf8 """ fileoperation(string): open,read,write,close """ #==================================== #importWinTxtReader编码异常模块调用 #==================================== importsys reload(sys) printsys.getdefaultencoding() sys.setdefaultencoding('utf-8') #============================== #打开文件txt1.txt,读取文本信息 #============================== f=open('string_rw.py','rb') a=f.read() f.close() #============================== #打开文件txt2.txt,读取文本信息 #============================== f=open('cPickle.py','rb') b=f.read() f.close() #==================================== #合并来自txt1.txt和txt2.txt的文本信息 #==================================== s=''#空字符串 a=s.join(list(a)[3:])#去掉utf-8编码BOM标记 b=s.join(list(b)[3:])#否则出现解码错误提示 l=list(a+'\n'+b)#字符串拆分 s=s.join(l)#字符串连接 #=================================== #新建,打开文件txt.txt,写入文本信息 #=================================== f=open('txt.py','wb') f.write(s) f.close() #============================= #打开文件txt.txt,读取文本信息 #============================= x=open('txt.py','rb') print(x.read().decode('utf-8'))#无BOM的utf-8解码 #=================================== #WinTxtReader.readTxt(x)编码异常输出 #=================================== Signupforfree tojointhisconversationonGitHub. Alreadyhaveanaccount? Signintocomment Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?