1.open()
打開文件
語(yǔ)法:open(path,method,encode)
path------>:文件的路徑
mechod--->:決定以什么方式打開文件 讀寫
encode--->:指定以什么編碼打開文件
f = open('./one.txt','r',encoding='utf-8')
for x in f:
print(x)
f.close()
with open('./one.txt','r',encoding='utf-8')as f:
print(f.read())
print(open('./one.txt','r',encoding='utf-8').read())
#將文本內(nèi)容以字符串輸出
f = open('./one.txt','a',encoding='utf-8')
f.write('yoooooooooooooooooop!')
f = open('./one.txt','w',encoding='utf-8')
f.write('清空原文件再寫入')
說(shuō)明:打開文件的方式:
'r'-讀操作:(讀出來(lái)是字符串)
'rb'/'br'-:讀操作(讀出來(lái)的數(shù)據(jù)是二進(jìn)制)
'w'-寫操作:(可以文本數(shù)據(jù)寫入文件中)如果文件不存在,‘w'操作會(huì)創(chuàng)建一個(gè)相應(yīng)的文件。
'wb'/'bw'-:寫操作(將二進(jìn)制數(shù)據(jù)寫入文件中)
'a’-寫操作:(追加)
音頻、視頻、圖片都是二進(jìn)制保存
2.with open() as
open()進(jìn)行文件操作時(shí),打開文件后操作完成后需要關(guān)閉文件對(duì)象。
而with open() as 創(chuàng)建文件對(duì)象時(shí),執(zhí)行完讀寫操作后會(huì)自動(dòng)關(guān)閉。
with open('./one.txt','r',encoding='utf-8')as f:
c = f.readline()
print(c)
with open('./one.txt','a',encoding='utf-8')as f:
f.write('\n追加寫入')
3.將字符串插入文本開頭
將內(nèi)容以字符串形式讀取出來(lái),將新內(nèi)容插入到字符串的開頭,再寫入這個(gè)字符串到文件
def fun(str,path='./one.txt'):
con = open(path).read()
temp = str + con
open(path,'r+').write(temp)
fun('a')
注意: r+表示可以寫入和讀取。寫入類似于 a
4.檢查一個(gè)文件是否是GIF文件
計(jì)算機(jī)中圖片、視頻、音頻文件都是以二進(jìn)制形式存儲(chǔ)
with open('./one.txt','rb')as f:
con = tuple(f.read(4))
if con==(0x47,0x49,0x46,0x38):
print('yes')
print('no')
no
說(shuō)明:所有g(shù)if文件開頭是以0x47,0x49,0x46,0x38開頭,所以二進(jìn)制讀取前4個(gè)的內(nèi)容進(jìn)行判斷。