Python 專題四 檔案基礎知識,
前面講述了函數、語句和字串的基礎知識,該篇文章主要講述檔案的基礎知識(與其他語言非常類似).
一. 檔案的基本操作
檔案是指儲存在外部介質(如磁碟)上資料的集合.檔案的操作流程為:
開啟檔案(讀方式\寫方式)->讀寫檔案(read\readline\readlines\write\writelines)->關閉檔案
1.開啟檔案
調用函數open開啟檔案,其函數格式為:
file_obj=open(filename[, mode[, buffering]]) 返回一個檔案對象(file object)
— filename檔案名稱(唯一強制參數)
·原始字串 r'c:\temp\test.txt'
·轉移字串 'c:\\temp\\test.txt'
— mode檔案模式
·r 讀模式
·w 寫入模式
·a 追加模式(寫在上次後面)
·+ 讀/寫入模式(沒有檔案即建立,可添加到其他模式中使用)
·b 二進位模式(可添加到其他模式中使用)
— buffering緩衝(選擇性參數)
·參數=0或False 輸入輸出I/O是無緩衝的,所有讀寫操作針對硬碟
·參數=1或True 輸入輸出I/O是有緩衝的,記憶體替代硬碟
·參數>1數字代表緩衝區的大小,單位位元組.-1或負數代表使用預設緩衝區大小
注意:當處理二進位檔案如聲音剪輯或映像時使用'b'二進位模式,可以'rb'讀取一個二進位檔案.
2.關閉檔案
應該牢記使用close方法關閉檔案,因為Python可能會緩衝(出於效率考慮把資料臨時儲存某處)寫入資料,如果程式突然崩潰,資料根本不會被寫入檔案,為安全起見,在使用完檔案後關閉.如果想確保檔案被關閉,應該使用try/finally語句,並且在finally子句中調用close方法.如:
#Open your file try: #Write data to your file finally: file.close()
3.讀寫檔案
調用函數write方法向檔案中寫入資料,其函數格式為:
file_obj.write(string) 參數string會被追加到檔案中已存部分後面
file_obj.writelines(sequence_of_strings) 僅傳遞一個參數,列表[ ] 元組() 字典{}
注意:實用字典時字串的順序出現是隨機的.
#使用write()寫檔案 file_obj=open('test.txt','w') str1='hello\n' str2='world\n' str3='python' file_obj.write(str1) file_obj.write(str2) file_obj.write(str3) file_obj.close() #使用writelines()寫檔案 file_obj=open('test.txt','w') str1='hello\n' str2='world\n' str3='python' file_obj.writelines([str1,str2,str3]) file_obj.close() #輸出 本地test.txt檔案 hello word python
調用函數read方法讀取資料,其函數格式為:var=file_obj.read(),其中read全部讀取,返回string;readline讀取一行,返回string;readlines讀取檔案所有行,返回a list of string.例:
#使用read print 'Use the read' file_obj=open('test.txt','r') s=file_obj.read() print s file_obj.close #使用readline print 'Use the readline' file_obj=open('test.txt','r') line1=file_obj.readline() line1=line1.rstrip('\n') print 'l1 ',line1 line2=file_obj.readline() line2=line2.rstrip('\n') print 'l2 ',line2 line3=file_obj.readline() line3=line3.rstrip('\n') print 'l3 ',line3 file_obj.close #使用readlines print 'Use the readlines' file_obj=open('test.txt','r') li=file_obj.readlines() print li file_obj.close
輸出內容如下:
Use the read hello world python Use the readline l1 hello l2 world l3 python Use the readlines ['hello\n', 'world\n', 'python']
可以發現在使用readline()函數時它返回的結果是'hello\n'字串,需要使用rstrip去除'\n',否則print輸出時總空一行.同時寫入檔案時使用格式化寫入比較方便,如s="xxx%dyyy%s\n"%(28,'csdn').
#格式化寫入 fd=open('format.txt','w') head="%-8s%-10s%-10s\n"%('Id','Name','Record') fd.write(head) item1="%-8d%-10s%-10.2f\n"%(10001,'Eastmount',78.9) fd.write(item1) item2="%-8d%-10s%-10.2f\n"%(10002,'CSDN',89.1234) fd.write(item2) fd.close() #輸出 Id Name Record 10001 Eastmount 78.90 10002 CSDN 89.12
二. 檔案與迴圈
前面介紹了檔案的基本操作和使用方法,但是檔案操作通常會與迴圈聯絡起來,下面介紹while迴圈和for迴圈實現檔案操作.代碼如下:
#使用while迴圈 fr=open('test.txt','r') str=fr.readline() str=str.rstrip('\n') while str!="": print str str=fr.readline() str=str.rstrip('\n') else: print 'End While' fr.close #使用for迴圈 rfile=open('test.txt','r') for s in rfile: s=s.rstrip('\n') print s print 'End for' rfile.close()
其中for調用迭代器iterator,迭代器提供一種方法順序訪問一個彙總對象中的各個元素,它相當於通過Iter函數擷取對象的迭代器,再通過next函數(該方法調用時不需要任何參數)擷取下一個值.for可以遍曆iterator_obj包括List\String\Tuple\Dict\File.如:
s='www.csdn.NET' si=iter(s) #產生迭代器 print si.next() #調用next依次擷取元素,最後迭代器沒有傳回值時引發StopIteration異常
三. 總結
該篇文章主要講述了Python檔案基礎知識,包括檔案的開啟、讀寫、關閉操作、使用迴圈讀寫檔案及迭代器的知識.希望對大家有所協助,如果有錯誤或不足之處,還請海涵!
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!