前面講述了函數(shù)、語句和字符串的基礎(chǔ)知識(shí),該篇文章主要講述文件的基礎(chǔ)知識(shí)(與其他語言非常類似).
一. 文件的基本操作
文件是指存儲(chǔ)在外部介質(zhì)(如磁盤)上數(shù)據(jù)的集合.文件的操作流程為:
打開文件(讀方式\寫方式)->讀寫文件(read\readline\readlines\write\writelines)->關(guān)閉文件
1.打開文件
調(diào)用函數(shù)open打開文件,其函數(shù)格式為:
file_obj=open(filename[, mode[, buffering]]) 返回一個(gè)文件對(duì)象(file object)
— filename文件名(唯一強(qiáng)制參數(shù))
·原始字符串 r'c:\temp\test.txt'
·轉(zhuǎn)移字符串 'c:\\temp\\test.txt'
— mode文件模式
·r 讀模式
·w 寫模式
·a 追加模式(寫在上次后面)
·+ 讀/寫模式(沒有文件即創(chuàng)建,可添加到其他模式中使用)
·b 二進(jìn)制模式(可添加到其他模式中使用)
— buffering緩沖(可選參數(shù))
·參數(shù)=0或False 輸入輸出I/O是無緩沖的,所有讀寫操作針對(duì)硬盤
·參數(shù)=1或True 輸入輸出I/O是有緩沖的,內(nèi)存替代硬盤
·參數(shù)>1數(shù)字代表緩沖區(qū)的大小,單位字節(jié).-1或負(fù)數(shù)代表使用默認(rèn)緩沖區(qū)大小
注意:當(dāng)處理二進(jìn)制文件如聲音剪輯或圖像時(shí)使用'b'二進(jìn)制模式,可以'rb'讀取一個(gè)二進(jìn)制文件.
2.關(guān)閉文件
應(yīng)該牢記使用close方法關(guān)閉文件,因?yàn)?a href="/article/82005.html">Python可能會(huì)緩存(出于效率考慮把數(shù)據(jù)臨時(shí)存儲(chǔ)某處)寫入數(shù)據(jù),如果程序突然崩潰,數(shù)據(jù)根本不會(huì)被寫入文件,為安全起見,在使用完文件后關(guān)閉.如果想確保文件被關(guān)閉,應(yīng)該使用try/finally語句,并且在finally子句中調(diào)用close方法.如:
1
2
3
4
5
|
#Open your file try : #Write data to your file finally : file .close() |
3.讀寫文件
調(diào)用函數(shù)write方法向文件中寫入數(shù)據(jù),其函數(shù)格式為:
file_obj.write(string) 參數(shù)string會(huì)被追加到文件中已存部分后面
file_obj.writelines(sequence_of_strings) 僅傳遞一個(gè)參數(shù),列表[ ] 元組() 字典{}
注意:實(shí)用字典時(shí)字符串的順序出現(xiàn)是隨機(jī)的.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#使用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 |
調(diào)用函數(shù)read方法讀取數(shù)據(jù),其函數(shù)格式為:var=file_obj.read(),其中read全部讀取,返回string;readline讀取一行,返回string;readlines讀取文件所有行,返回a list of string.例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#使用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 |
輸出內(nèi)容如下:
1
2
3
4
5
6
7
8
9
10
|
Use the read hello world python Use the readline l1 hello l2 world l3 python Use the readlines ['hello\n', 'world\n', 'python'] |
可以發(fā)現(xiàn)在使用readline()函數(shù)時(shí)它返回的結(jié)果是'hello\n'字符串,需要使用rstrip去除'\n',否則print輸出時(shí)總空一行.同時(shí)寫入文件時(shí)使用格式化寫入比較方便,如s="xxx%dyyy%s\n"%(28,'csdn').
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#格式化寫入 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 |
二. 文件與循環(huán)
前面介紹了文件的基本操作和使用方法,但是文件操作通常會(huì)與循環(huán)聯(lián)系起來,下面介紹while循環(huán)和for循環(huán)實(shí)現(xiàn)文件操作.代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#使用while循環(huán) 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循環(huán) rfile = open ( 'test.txt' , 'r' ) for s in rfile: s = s.rstrip( '\n' ) print s print 'End for' rfile.close() |
其中for調(diào)用迭代器iterator,迭代器提供一種方法順序訪問一個(gè)聚合對(duì)象中的各個(gè)元素,它相當(dāng)于通過Iter函數(shù)獲取對(duì)象的迭代器,再通過next函數(shù)(該方法調(diào)用時(shí)不需要任何參數(shù))獲取下一個(gè)值.for可以遍歷iterator_obj包括List\String\Tuple\Dict\File.如:
1
2
3
|
s = 'www.csdn.NET' si = iter (s) #生成迭代器 print si. next () #調(diào)用next依次獲取元素,最后迭代器沒有返回值時(shí)引發(fā)StopIteration異常 |
三. 總結(jié)
該篇文章主要講述了Python文件基礎(chǔ)知識(shí),包括文件的打開、讀寫、關(guān)閉操作、使用循環(huán)讀寫文件及迭代器的知識(shí).希望對(duì)大家有所幫助,如果有錯(cuò)誤或不足之處,還請(qǐng)海涵!
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持服務(wù)器之家!
原文鏈接:http://blog.csdn.net/eastmount/article/details/39854689