1. 程式人生 > >Python學習日記:day8-------文件操作

Python學習日記:day8-------文件操作

pen 全部 readline 類型 see closed odin 相對 操作

文件操作

1,文件路徑:d:\xxxx.txt 絕對路徑:從根目錄到最後 相對路徑:當前目錄下的文件 2,編碼方式:utf-8 3,操作方式:只讀,只寫,追加,讀寫,寫讀...... (1)只讀--r 技術分享圖片
f =open(路徑,mode=r,encoding=編碼方式)
content=f.read()
print(content)
f.close() 
只讀-r 以什麽編碼方式儲存的文件,就要以什麽編碼方式打開。 只讀:r----->以str方式讀取 只讀; rb------>以bytes類型打開,用於非文字文件的打開. (2)只寫-->沒有此文件就會創建文件。有個文件則會先將源文件的內容全部清除,再寫。 只寫:w f =open(‘路徑‘,mode=‘w‘,encoding=‘編碼方式‘)
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(‘+7‘)     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---》str: 1,decode(解碼) s1 = b.decode(‘utf-8‘) 2,如果字符串裏都是字母 解碼的時候寫gbk並不會報錯 技術分享圖片
s =abf
b=s.encode(utf-8)

print(b)

s1 =b.decode(gbk)

print(s1)

 
編碼與解碼

Python學習日記:day8-------文件操作