讀寫文件時(shí)應(yīng)注意的問(wèn)題包括:
1.字符編碼
2.操作完成即時(shí)關(guān)閉文件描述符
3.代碼兼容性
幾種方法:
#!/bin/python3 original_list1=[" "] original_list2=[" "] original_list3=[" "] original_list4=[" "] newlist1=[" "] newlist2=[" "] newlist3=[" "] newlist4=[" "] newtxt1="" newtxt2="" newtxt3="" newtxt4="" #first way to readline f = open("duplicate_txt.txt","r+") # 返回一個(gè)文件對(duì)象 line = f.readline() # 調(diào)用文件的 readline()方法 while line: original_list1.append(line) line = f.readline() f.close() #use "set()" remove duplicate str in the list # in this way,list will sort randomly newlist1 = list(set(original_list1)) #newlist1 = {}.fromkeys(original_list1).keys() #faster #rebuild a new txt newtxt1="".join(newlist1) f1 = open("noduplicate1.txt","w") f1.write(newtxt1) f1.close() ################################################################### #second way to readline for line in open("duplicate_txt.txt","r+"): original_list2.append(line) newlist2 = list(set(original_list2)) newlist2.sort(key=original_list2.index) #sort #newlist2 = sorted(set(original_list2),key=l1.index) #other way newtxt2="".join(newlist2) f2 = open("noduplicate2.txt","w") f2.write(newtxt2) f2.close() ################################################################### #third way to readline f3 = open("duplicate_txt.txt","r") original_list3 = f3.readlines() #讀取全部?jī)?nèi)容 ,并以列表方式返回 for i in original_list3: #遍歷去重 if not i in newlist3: newlist3.append(i) newtxt3="".join(newlist3) f4 = open("noduplicate3.txt","w") f4.write(newtxt3) f4.close() ################################################################### #fourth way f5 = open('duplicate_txt.txt',"r+") try: original_list4 = f5.readlines() [newlist4.append(i) for i in original_list4 if not i in newlist4] newtxt4="".join(newlist4) f6 = open("noduplicate4.txt","w") f6.write(newtxt4) f6.close() finally: f5.close()
結(jié)果:
去重前:
去重后(無(wú)序):
去重后(有序):
總結(jié)
這段下程序涉及文件讀寫操作以及鏈表List的操作,文章開(kāi)頭提到的幾個(gè)問(wèn)題,由于并沒(méi)有使用中文,所以不關(guān)心編碼,但這里還是要提一提:
f = open("test.txt","w") f.write(u"你好")
上面這段代碼如果在python2中運(yùn)行會(huì)報(bào)錯(cuò)
報(bào)錯(cuò)是因?yàn)槌绦驔](méi)辦法直接保存unicode字符串,要經(jīng)過(guò)編碼轉(zhuǎn)換成str類型的二進(jìn)制字節(jié)序列才可以保存。
write()方法會(huì)自動(dòng)編碼轉(zhuǎn)換,默認(rèn)使用ascii編碼格式,而ascii不能處理中文,所以出現(xiàn)UnicodeEncodeError。
正確方式是在調(diào)用write()方法前,手動(dòng)格式轉(zhuǎn)換,用utf-8或者gbk轉(zhuǎn)換成str。
f = open("test.txt","w") text=u"你好" text=text.encode(encoding='utf-8') f.write(text)
關(guān)于close()問(wèn)題:
不關(guān)閉會(huì)有什么影響呢?操作完成后,不關(guān)閉文件,會(huì)對(duì)系統(tǒng)資源造成浪費(fèi),因?yàn)橄到y(tǒng)可打開(kāi)的文件描述符數(shù)量是有限的。Linux是65535。
一般來(lái)說(shuō)close之后就OK了,但是也會(huì)存在特殊情況,比如說(shuō),在調(diào)用open()函數(shù)時(shí)就已經(jīng)發(fā)生錯(cuò)誤,權(quán)限不足,調(diào)用close()肯定報(bào)錯(cuò)。還有一種是在write()時(shí),如果磁盤空間不足,報(bào)錯(cuò),close()就沒(méi)有機(jī)會(huì)執(zhí)行了。正確的做法就是使用 try except 對(duì)異常進(jìn)行捕獲:
f = open("test.txt","w") try: text=u"你好" text=text.encode(encoding='utf-8') f.write(text) except: IOError as e: print("oops,%s"%e.args[0]) finally: f.close()
更優(yōu)雅的寫法是用 with…as。
with open("test.txt","w") as f: text=u"你好" f.write(text.encode(encoding='utf-8'))
文件對(duì)象實(shí)現(xiàn)上下午管理器協(xié)議,程序進(jìn)入with語(yǔ)句時(shí),會(huì)把文件對(duì)象賦值給變量f,在程序退出with時(shí)會(huì)自動(dòng)的調(diào)用close()方法。
關(guān)于兼容性問(wèn)題:
python2和python3的open()函數(shù)是不一樣的,后者可以在函數(shù)中指定字符編碼格式。
如何解決python2和python3的兼容open()問(wèn)題呢?
使用io模塊下的open()函數(shù),python2中的io.open等價(jià)與python3的open函數(shù)
from io import open with open("test.txt","w",encoding='utf-8') as f: f.write(u"你好")
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com