標籤:int() 讀取 lines lin coding readline 判斷 建立 進位
# r模式,預設模式,檔案不存在則報錯# w模式,檔案存在覆蓋,檔案不存在則建立# a模式,檔案不存在則建立,檔案存在不會覆蓋,寫內容是追加的方式.# 檔案處理--讀f = open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)# print(‘first-read:‘,f.read()) #讀取檔案所有內容,# f.seek(0) #可移動游標,括弧內指定數字就是指定位元組,需要注意一個中文對應3個位元組# f.seek(0) #可移動游標,括弧內指定數字就是指定位元組,需要注意一個中文對應3個位元組# print(‘seconde-read:‘,f.read()) #讀取檔案所有內容# print(f.read(13)) #括弧內可指定讀取字元所在的位置。# print(f.readline(),end=‘‘) #列印游標所在的當前行# print(f.readlines(),end=‘‘) #檔案內的所有字元,以列表的形式一行列印出來#檔案處理--寫#如果對應路徑沒有該檔案則建立一個檔案,如果有則清空檔案內容,並且寫入新的內容# f = open(‘b.txt‘,‘w‘,encoding=‘utf-8‘)# f.write(‘3333\n‘) #只能以字串的形式寫資料# f.write(‘4444\n‘)# print(‘資料寫入完畢!‘)# f.writelines([‘1111\n‘,‘2222\n‘,‘3333\n‘])# print(‘資料寫入完畢!‘)# print()# f.close()# 檔案處理--開啟# f = open(‘a.txt‘,‘a‘,encoding=‘utf-8‘)# f.truncate(3) #截斷#檔案處理--其它# f = open(‘b.txt‘,‘w‘,encoding=‘utf-8‘)# f.write(‘asfsadfgw‘)# f.flush() #立即把記憶體的資料刷到硬碟去# f.close() #關閉檔案# print(f.close()) #判斷檔案是否關閉# print(f.readable()) #判斷檔案是否可讀# print(f.writable()) #判斷檔案是否可寫# f.seek(0)# print(f.tell()) #輸出當前游標位置# print(f.read()) #列印全文# f.name,f.encoding# f = open(‘a.txt‘,‘w‘,encoding=‘utf-8‘)# f.truncate(10) #括弧內指定寫入字元數#檔案處理--# f = open(‘b.txt‘,‘w‘,encoding=‘utf-8‘)# f.write(‘44444\n‘)# f.write(‘55555\n‘)# f.close()# 補充# f = open(‘a.txt‘,‘rb‘)# print(f.read()) #以二進位的方式讀取# print(f.read().decode(‘utf-8‘)) #將二進位轉換為字串,後面備忘解碼方式# f=open(‘a.txt‘,‘wb‘)# f.write(‘你好啊,大叔‘.encode(‘utf-8‘))## f.a
python基礎之檔案處理