python文件操做

文件操做模式

 

讀取文件

文件內容緩存

牀前明月光,疑是地上霜
舉頭望明月,低頭思故鄉

1.read()網絡

讀取文件全部內容編碼

f = open('libai',encoding = 'utf-8')
print(f.read())

牀前明月光,疑是地上霜
舉頭望明月,低頭思故鄉

2.readline()spa

只讀取一行內容code

f = open('libai',encoding = 'utf-8')

print(f.readline())

牀前明月光,疑是地上霜

3.readlines()blog

把文章以換行符分割i,並生成list格式(數據量大的時候,不建議使用)ip

f = open('libai',encoding = 'utf-8')

print(f.readlines())

['牀前明月光,疑是地上霜\n', '舉頭望明月,低頭思故鄉']

4.seek和tell光標內存

f = open('libai',encoding='utf-8')
data = f.read()     #默認光標在起始的位置,read()讀取完後,光標停留到文件末尾
data2 = f.read()    #data2讀取的內容爲空
print(data)
print(data2)
f.close()          #關閉文件

 

文件內容utf-8

abcdefg
hyjklmn
opqrstu
vwxyz
f = open('libai',encoding='utf-8')
#tell獲取當前的光標
print(f.tell())    #0

print(f.readline().strip())
print(f.readline().strip())
print(f.tell())
f.seek(0)     #移動光標到文件起始的地方
print(f.readline().strip())


結果:
0
abcdefg
hyjklmn
18
abcdefg

 

5.flush刷新it

模擬進度條

import sys,time

for i in range(40):
    sys.stdout.write('#')
    sys.stdout.flush()     #flush強制舒心緩存到內存的數據寫入硬盤
    time.sleep(0.1)

 

6.with語句

with代碼執行完後,文件會自動關閉

with open('libai') as f:
    print(f.read())

 

7.二進制讀取"rb"

#rb  二進制模式讀取
f = open('libai','rb')  #主要用於網絡傳輸
print(f.readline())


b'\xe5\xba\x8a\xe5\x89\x8d\xe6\x98\x8e\xe6\x9c\x88\xe5\x85\x89\xef\xbc\x8c\xe7\x96\x91\xe6\x98\xaf\xe5\x9c\xb0\xe4\xb8\x8a\xe9\x9c\x9c\r\n'

8.二進制寫"wb"

f = open('libai','wb')
f.write('中文'.encode()) 

 

編碼與轉換

方法

相關文章
相關標籤/搜索