Python 文件操作的詳解及實(shí)例
一、文件操作
1、對(duì)文件操作流程
打開文件,得到文件句柄并賦值給一個(gè)變量 通過句柄對(duì)文件進(jìn)行操作 關(guān)閉文件現(xiàn)有文件如下:
昨夜寒蛩不住鳴。驚回千里夢(mèng),已三更。起來獨(dú)自繞階行。人悄悄,簾外月朧明。白首為功名,舊山松竹老,阻歸程。欲將心事付瑤琴。知音少,弦斷有誰聽。f = open('小重山') #打開文件data=f.read()#獲取文件內(nèi)容f.close() #關(guān)閉文件注意:if in the win,hello文件是utf8保存的,打開文件時(shí)open函數(shù)是通過操作系統(tǒng)打開的文件,而win操作系統(tǒng)默認(rèn)的是gbk編碼,所以直接打開會(huì)亂碼,需要f=open(‘hello',encoding='utf8'),hello文件如果是gbk保存的,則直接打開即可。
2、文件打開模式
Character Meaning
'r' open for reading (default)'w' open for writing, truncating the file first'x' create a new file and open it for writing'a' open for writing, appending to the end of the file if it exists'b' binary mode't' text mode (default)'+' open a disk file for updating (reading and writing)'U' universal newline mode (deprecated)
先介紹三種最基本的模式:
# f = open('小重山2','w') #打開文件# f = open('小重山2','a') #打開文件# f.write('莫等閑1/n')# f.write('白了少年頭2/n')# f.write('空悲切!3')3、文件具體操作
f = open('小重山') #打開文件# data1=f.read()#獲取文件內(nèi)容# data2=f.read()#獲取文件內(nèi)容## print(data1)# print('...',data2)# data=f.read(5)#獲取文件內(nèi)容# data=f.readline()# data=f.readline()# print(f.__iter__().__next__())# for i in range(5):# print(f.readline())# data=f.readlines()# for line in f.readlines():# print(line)# 問題來了:打印所有行,另外第3行后面加上:'end 3'# for index,line in enumerate(f.readlines()):# if index==2:# line=''.join([line.strip(),'end 3'])# print(line.strip())#切記:以后我們一定都用下面這種# count=0# for line in f:# if count==3:# line=''.join([line.strip(),'end 3'])# print(line.strip())# count+=1# print(f.tell())# print(f.readline())# print(f.tell())#tell對(duì)于英文字符就是占一個(gè),中文字符占三個(gè),區(qū)分與read()的不同.# print(f.read(5))#一個(gè)中文占三個(gè)字符# print(f.tell())# f.seek(0)# print(f.read(6))#read后不管是中文字符還是英文字符,都統(tǒng)一算一個(gè)單位,read(6),此刻就讀了6個(gè)中文字符#terminal上操作:f = open('小重山2','w')# f.write('hello /n')# f.flush()# f.write('world')# 應(yīng)用:進(jìn)度條# import time,sys# for i in range(30):# sys.stdout.write("*")# # sys.stdout.flush()# time.sleep(0.1)# f = open('小重山2','w')# f.truncate()#全部截?cái)? f.truncate(5)#全部截?cái)? print(f.isatty())# print(f.seekable())# print(f.readable())f.close() #關(guān)閉文件
新聞熱點(diǎn)
疑難解答
圖片精選