Python學習之路:文件操作之增刪改查
阿新 • • 發佈:2017-11-02
打印 odin day 打開 aps 之前 編碼 數據 adl
f = open("yesterday","r",encoding="utf-8") #print(f.read()) #for i in range(5): # print(f.readline()) #打印前5行 #low loop ‘‘‘ for index,line in enumerate(f.readline()): if index == 9: print(‘---------我是分割線---------‘) continue print(line.strip()) ‘‘‘ # high bige ‘‘‘ count =0 for line in f: if count==9: print(‘---------我是分割線-----‘) count +=1 continue print(line) #效率最高,一行一行的讀 count +=1 ‘‘‘ f =open("yesterday2","w",encoding="utf-8") f.write("hello1\n") f.write("hello2\n") f.write("hello3\n") f.flush()#實現數據從緩存刷到硬盤 ‘‘‘ print(f.tell()) #查詢光標位置 print(f.readline()) print(f.tell())#查詢光標位置,按字符計數 print(f.read(5)) print(f.tell()) f.seek(0)#光標回到某個字符位置 print(f.readline()) f.seek(10) print(f.readline()) print(f.encoding)#打印文件編碼 print(f.fileno()) #讀取文件編號 #print(f.flush()) print(dir(f.buffer)) ‘‘‘ ‘‘‘#進度條實現 import sys,time for i in range(50): sys.stdout.write("#") sys.stdout.flush() time.sleep(0.1) ‘‘‘ f = open("yesterday","a+",encoding="utf-8")#追加讀寫 #f.truncate(10) #截斷 f.seek(10) f.truncate(20) #可以打開,追加 f = open("yesterday","r+",encoding="utf-8")#讀寫 print(f.readline()) print(f.readline()) print(f.readline()) print(f.tell()) f.write(‘--------niu----------‘) #用處不大 f = open("yesterday","w+",encoding="utf-8")#寫讀 f.write(‘--------niu----------1\n‘) f.write(‘--------niu----------2\n‘) f.write(‘--------niu----------3\n‘) print(f.tell()) f.seek(10) #不能在中間插入,只能繼續往後寫,或者覆蓋之前的 print(f.tell()) #使用場景:網絡傳輸只能用二進制 f = open("yesterday","rb")#以二進制格式讀文件 print(f.readline()) print(f.readline()) print(f.readline()) f = open("yesterday","wb")#以二進制格式寫文件 f.write("hello binary\n".encode()) f = open("yesterday","ab")#以二進制格式追加文件
Python學習之路:文件操作之增刪改查