day8:文件操作
1,只讀方式打開文件,絕對路徑,打開文件,操作文件,關(guān)閉文件,file=和 mode= 可以去掉
f = open(file="/Users/guolixiao/Desktop/lisa.txt",mode="r") content = f.read() print(content)f.close #別忘了關(guān)閉文件 # 編碼方式,我理解的是OS決定的,默認(rèn)都是UTF-8,但是Windows默認(rèn)是GBK,如果應(yīng)用軟件指定了,那就按照應(yīng)用軟件的來,沒指定按照操作系統(tǒng)默認(rèn)的 # 不知道對不對 # 絕對路徑打開 # mode參數(shù)本來就是第二個(gè),可以按照位置參數(shù)來打開,但是指定編碼的是第四個(gè),必須按照關(guān)鍵字參數(shù)打開 # pycharm 默認(rèn)編碼是UTF-8,字符串在內(nèi)存里面默認(rèn)是Ascii碼,pycharm自動給進(jìn)行了轉(zhuǎn)化,但是文件這種,需要人為指定 # Mac的linux默認(rèn)是UTF-8,也可以不指定,但是Windows默認(rèn)是GBK必須指定 # 文件如果保存成GBK,打開方式也是GBK,那么pycharm軟件也得改成GBK,不然還是現(xiàn)實(shí)亂碼,因?yàn)閜ycharm會用UTF-8去解碼GBK, # 也就是你雖然用GBK打開了,但是你讀的時(shí)候,沒有用GBK去解碼,而是用的UTF-8 運(yùn)行結(jié)果: my name is lisa,I am 22 years old
2,文件打開模式,r,r+,r+b,w,w+,w+b,a,a+,a+b,其中r和r+用的最多,推薦
3,先說讀模式相對路徑打開
f = open("../link/lisa2","r") content = f.read() print(content) f.close #別忘了關(guān)閉文件 運(yùn)行結(jié)果: hello,everyone4,存儲的讀取的編碼方式不一樣,會出現(xiàn)亂碼,以什么方式存儲的文件,就要以什么方式打開操作
f = open("../link/lisa2","r",encoding="GBK") content = f.read() print(content) f.close #別忘了關(guān)閉文件 運(yùn)行結(jié)果: 浣犲ソ錛屽ぇ瀹跺ソ5,rb方式打開,以 bytes方式打開,不可以指定編碼方式了,一般這種打開一些非文字文件,例如:圖片,視頻,音頻等
f = open("../link/lisa2","rb") content = f.read() print(content) f.close #別忘了關(guān)閉文件 運(yùn)行結(jié)果: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd'6,用r這種方式讀出來的內(nèi)容是str類型的,rb這種是bytes類型的
f = open("../link/lisa2","rb") content = f.read() print(content,type(content)) f.close()f = open("../link/lisa2","r") content = f.read() print(content,type(content)) f.close()運(yùn)行結(jié)果: b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd' <class 'bytes'> 你好,大家好 <class 'str'>7,寫模式w,注意如果以寫的模式打開,那么文件存在,清空寫,如果文件不存在,創(chuàng)建文件,清空寫,很霸道的模式,所以也是創(chuàng)建文件的一種方式
f = open('file_log.txt',"w",encoding="UTF-8") f.write("hellohellohellohello") f.close() # UTF-8 不區(qū)分大小寫,都可以8,wb模式寫,注意寫之前的文字要編碼在寫,不然寫不進(jìn)去
f = open('file_log.txt',"wb") s ="hellohellohellohello" f.write(s.encode()) f.close()9,追加模式寫,追加模式不會清空原有文件,會在后面寫,和上面的寫一樣,a模式windows下別忘了加encoding,ab模式寫之前要編碼
10,默認(rèn)只讀打開不可以寫,只寫打開不可以讀
11,讀寫的話,需要用到加模式 先說r+
f = open('file_log.txt',"r+") print(f.read()) f.write("world") print(f.read()) f.close()運(yùn)行結(jié)果: hellohellohellohello 運(yùn)行完之后文件里面內(nèi)容: hellohellohellohelloworld運(yùn)行前文件內(nèi)容:
hellohellohellohello分析:第一次打印完,指針到了最后,所以在最后寫了world,然而這時(shí)候指針到了最后,第二句打印就沒有什么可以打印的了,read和write完全是根據(jù)指針來的
12,來看另外一個(gè)r+的示例,r+b 比較簡單不再掩飾
# 先寫后讀會覆蓋,先讀后寫會追加 f = open('file_log.txt',"r+") f.write("world") print(f.read()) f.close()運(yùn)行結(jié)果: hellohellohello 運(yùn)行完之后文件里面內(nèi)容: worldhellohellohello
運(yùn)行前文件內(nèi)容:
hellohellohellohello
打印永遠(yuǎn)是從當(dāng)前指針開始
13,由于每次寫之后,指針位置變了,read不到全部的文件,所以有了指針設(shè)定函數(shù)seek
f = open('file_log.txt',"r+") f.write("world") f.seek(0) print(f.read()) f.close()運(yùn)行結(jié)果: worldhellohellohello打印出了所有文件14,read 函數(shù)是按照字符來取得,seek函數(shù)是按照字節(jié)設(shè)置的
f = open('file_log.txt',"r+") f.seek(2) print(f.read()) f.close()文件內(nèi)容: 大家好,很高興認(rèn)識大家運(yùn)行結(jié)果: Traceback (most recent call last):File "/Users/guolixiao/PycharmProjects/lisa's_practise/boys/8.1_文件操作.py", line 61, in <module>print(f.read())File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode(result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa7 in position 0: invalid start byte 分析: 由于文件內(nèi)容是中文,每個(gè)漢字占用3個(gè)字節(jié),所以seek設(shè)置必須為3的倍數(shù)15,另外一個(gè)seek的例子
f = open('file_log.txt',"r+") f.seek(3) print(f.read(3)) f.close()運(yùn)行結(jié)果: 家好,seek設(shè)置為3,指針往后走了1個(gè)漢字,但是read參數(shù)3得話,往后走了3個(gè)漢字16,獲取光標(biāo)位置tell函數(shù)
f = open('file_log.txt',"r+") f.seek(3) print(f.tell()) f.close()運(yùn)行結(jié)果: 317,
# 打印最后3的字節(jié),也就是一個(gè)漢字, 先讀出來指針位置,再設(shè)置指針,然后再讀 f = open('file_log.txt',"a+") f.write('你們好') count =f.tell() print(count) content = f.seek(count-3) print(f.read()) f.close()運(yùn)行結(jié)果: 51 好?18,readable,writable函數(shù),判斷文件是否可讀可寫,用的不多,了解即可
?19,文件一下子全部讀進(jìn)來,如果文件比較大的話,可能會造成系統(tǒng)崩潰,所以我們可以用readline來讀,非文字的可以用size比如1024來循環(huán)讀
20,readline 和readlines 的區(qū)別
f = open('file_log.txt',"r+") content=f.readline() print(content) # 不循環(huán)只讀一行 f.close()f = open('file_log.txt',"r+") content=f.readlines() #讀成了列表 print(content) f.close()運(yùn)行結(jié)果: 我們好['我們好\n', '你們好\n', '他們好\n', '大家都好\n']21,截取文件的一段truncate函數(shù)
f = open('file_log.txt',"r+") f.truncate(9) f.close()運(yùn)行完之后,文件里面只剩下最前面的三個(gè)漢字了22,for循環(huán)可以readline
f = open('file_log.txt',"r+") for line in f: # 注意是f 不是f.readline,第二,文件里面已經(jīng)有一個(gè)換行符號了,print還會再加一個(gè)print(line) f.close()運(yùn)行結(jié)果: 我們好你們好他們好大家都好 f = open('file_log.txt',"r+") for line in f: # 注意是f 不是f.readline,第二,文件里面已經(jīng)有一個(gè)換行符號了,print還會再加一個(gè)print(line,end="") f.close()運(yùn)行結(jié)果: 我們好 你們好 他們好 大家都好23,由于每次打開文件,都要關(guān)閉,如果嫌棄麻煩,可以用with open方式打開,還可以一次打開多個(gè)文件,推薦使用,一般as 后面的名字是obj,或者f 啥啥的
with open('file_log.txt',"r+") as f1, open("lisa.txt","w+") as f2:print(f1.read())print("-----------------")f2.write("hellllllll")f2.seek(0)print(f2.read())運(yùn)行結(jié)果: 我們好 你們好 他們好 大家都好 ----------------- hellllllll with open('file_log.txt',"r+") as f1, \open("lisa.txt","w+") as f2:print(f1.read())print("-----------------")f2.write("hellllllll")f2.seek(0)print(f2.read())24,最后一個(gè)示例,用戶名密碼,三次錯(cuò)誤,則拒絕登錄
# 注冊創(chuàng)建用戶,并儲存在文件中,至于什么strip特殊字符啥的,這里先不考慮了 usrname = input("please input username:") pwd = input("please input password:") with open("usr.txt","w",encoding="utf-8") as obj:# obj.write(usrname,pwd) # 每次只可以加一個(gè)參數(shù),錯(cuò)誤,我們想顯示成lisa換行123# obj.write(usrname)# obj.write("\n")# obj.write(pwd) # 中間還要單獨(dú)加個(gè)空格,三行代碼,麻煩,我們有更簡單的一行搞定,format函數(shù)obj.write("{}\n{}".format(usrname,pwd)) # 注冊完成了,下面開始登陸的邏輯了 i = 0 while i < 3:usr = input("login username:")pwd = input("login password:")with open("usr.txt","r") as obj:li = obj.readlines()if li[0].strip() == usr and li[1].strip()==pwd:print("success")breakelse:print("wrong account")i = i + 1 # 注意strip函數(shù)可以把換行符號也strip掉的?
轉(zhuǎn)載于:https://www.cnblogs.com/lisa-blog/p/10036315.html
總結(jié)
- 上一篇: android学习日记12--布局管理器
- 下一篇: 如何在WinForm中发送HTTP请求