1. 程式人生 > >文件操作方法

文件操作方法

目錄下的文件 相對 全部 字符 元素 post adl 沒有 read

文件路徑:d:\zzz\xxxx.txt,一定註意光標問題!!!seek(),寫完光標在最後要往前提

1、絕對路徑:從根目錄到現在目錄 2、相對路徑:當前目錄下的文件,同級 2,編碼方式:utf-8 3,操作方式:只讀,只寫,追加,讀寫,寫讀 (1)只讀--r f.read() 以什麽編碼方式儲存的文件,就要以什麽編碼方式打開。 只讀:r轉換為str方式讀取 只讀; rb以bytes類型打開,用於非文字文件(圖片,pdf)的打開. (2)只寫沒有此文件就會創建文件。有個文件則會先將源文件的內容全部清除,再寫。 只寫:w f =open(‘文件路徑‘,mode=‘w‘,encoding=‘編碼方式(一般為utf-8或則gbk)‘) content=f.write(‘內容‘) f.close() wb: f =open(‘文件路徑‘,mode=‘wb‘) content=f.write(‘內容‘.encode(‘utf-8‘)) f.close() (3)追加在文件後追加內容:a f =open(‘文件路徑‘,mode=‘a‘,encoding =‘編碼方式‘) f.write(‘內容‘) f.close() ab f =open(‘文件路徑‘,mode=‘a‘) f.write(‘內容‘,encode(‘utf-8‘)) f.close() (4)r+(先讀後寫) 讀寫: f = open(‘log‘,mode =‘r+‘,encoding=‘utf-8‘) content =f print(f.read()) f.write(‘內容‘) f.close() (5)寫讀:(先寫後讀) f = open(‘log‘,mode =‘r+‘,encoding=‘utf-8‘) content =f f.write(‘內容‘) print(f.read()) f.close() 先寫後讀。先寫,光標從開頭往後走,覆蓋後邊的內容。 (6)r+模式的bytes類型:r+b f = open(‘log‘,mode =‘r+b‘) print(f.read()) f.write(‘內容‘.encode(‘編碼方式‘)) f.close() (7)w+ f =open(‘文件路徑‘,mode=‘w+‘,encoding =‘utf-8‘) f.write(‘內容‘) print(f.read()) f.close() 4、seek:調光標 f.seek(位置)-----》f.seek(0) ‘‘‘ read是按字符來讀。 seek是按字節去定光標的位置 ‘‘‘ f =open(‘log‘,mode = ‘r+‘,encodeing=‘utf-8‘) f.seek(3) content =f.read() print(content) f.close() 5、電影中下載斷點續傳方法,即定位光標的位置   f.tell()定位光標的位置     f =open(‘log‘,mode = ‘a+‘,encoding =‘utf-8‘)     f.write(‘a‘)     count =f.tell()     f.seek(count -9)#在utf-8中一個中文占三個字節     print(f.read())     f.close() 6、f.readable() 判斷是不是可讀返回值true或false line =f.readline() print(line) f.close() 7、redline 一行一行讀 line = f.readlines() print(line) f.close() 每一行當成列表中的一個元素,添加到列表中(lines是列表) truncate 截取一段去讀 8、用with打開文件 with open(‘文件路徑‘,mode=‘r‘,encoding=‘utf-8‘) as obj: print(obj.read()) 打開多個文件 技術分享圖片
編碼二 bytes轉換為ustr: 1,decode(解碼) s1 = b.decode(‘utf-8‘) 2,如果字符串裏都是字母 解碼的時候寫gbk並不會報錯

文件操作方法