第十一章 文件
第十一章 文件
打開(kāi)文件
當(dāng)前目錄中有一個(gè)名為beyond.txt的文本文件,打開(kāi)該文件
調(diào)用open時(shí),原本可以不指定模式,因?yàn)槠淠J(rèn)值就是’r’。
文件模式
| ‘r’ | 讀取模式(默認(rèn)值) |
| ‘w’ | 寫(xiě)入模式 |
| ‘x’ | 獨(dú)占寫(xiě)入模式 |
| ‘a(chǎn)’ | 附加模式 |
| ‘b’ | 二進(jìn)制模式(與其他模式結(jié)合使用) |
| ‘t’ | 文本模式(默認(rèn)值,與其他模式結(jié)合使用) |
| ‘+’ | 讀寫(xiě)模式(與其他模式結(jié)合使用) |
文件的基本方法
讀取和寫(xiě)入
在當(dāng)前路徑下創(chuàng)建一個(gè)beyond.txt文本文件,在該文本文件中寫(xiě)入內(nèi)容,并讀取出來(lái)。
import io f = open('beyond.txt','w') f.write("I like beyond band")#結(jié)果為:18 f.write("I like wsq")#結(jié)果為:10 f.close()運(yùn)行結(jié)果如下:
import io f = open('beyond.txt','r') f.read(4)#結(jié)果為:'I li' f.read()#結(jié)果為:'ke beyond bandI like wsq'首先,指定了要讀取多少(4)個(gè)字符。接下來(lái),讀取了文件中余下的全部?jī)?nèi)容(不指定要讀取多少個(gè)字符)。
使用管道重定向輸出
在bash等shell中,可依次輸入多個(gè)命令,并使用管道將它們鏈接起來(lái)
$ cat beyond.txt | python somescript.py | sort
cat beyond.txt:將文件beyond.txt的內(nèi)容寫(xiě)入到標(biāo)準(zhǔn)輸出(sys.stdout)。
python somescript.py:執(zhí)行Python腳本somescript。這個(gè)腳本從其標(biāo)準(zhǔn)輸入中讀取,并將結(jié)果寫(xiě)入到標(biāo)準(zhǔn)輸出。
sort:讀取標(biāo)準(zhǔn)輸入(sys.stdin)中的所有文本,將各行按字母順序排序,并將結(jié)果寫(xiě)入到標(biāo)準(zhǔn)輸出。
somescript.py從其sys.stdin中讀取數(shù)據(jù)(這些數(shù)據(jù)是beyond.txt寫(xiě)入的),并將結(jié)果寫(xiě)入到其sys.stdout(sort將從這里獲取數(shù)據(jù))。
計(jì)算sys.stdin中包含多少個(gè)單詞的簡(jiǎn)單腳本
somescript.py代碼如下:
beyond.txt內(nèi)容如下:
Yellow Skies, I can see the Yellow Skies. See you again, I see you again In my dreams, in my dreams, in my dreams, in my dreams. Morning light, I remember morning light. Outside my doors, I ll see you no more. In my dreams, in my dreams, in my dreams, in my dreams Forever, Forever Ill be forever holding you. Forever, Forever Ill be forever holding you. Responsible, Responsible, Responsible, Responsible. So black and white, Its become so black and white.cat beyond.txt | python somescript.py
隨機(jī)存取
所有的文件都可以當(dāng)成流來(lái)進(jìn)行處理,可以在文件中進(jìn)行移動(dòng),這稱為隨機(jī)存取。
可使用文件對(duì)象的兩個(gè)方法:seek 和 tell。
方法 seek(offset[, whence])將當(dāng)前位置(執(zhí)行讀取或?qū)懭氲奈恢?#xff09;移到 offset 和whence 指定的地方。
參數(shù) offset 指定了字節(jié)(字符)數(shù)
參數(shù) whence 默認(rèn)為 io.SEEK_SET(0),這意味著偏移量是相對(duì)于文件開(kāi)頭的(偏移量不能為負(fù)數(shù))。
讀取和寫(xiě)入行
讀取一行(從當(dāng)前位置到下一個(gè)分行符的文本),可使用方法readline。
可不提供任何參數(shù)(在這種情況下,將讀取一行并返回它)
也可提供一個(gè)非負(fù)整數(shù),指定readline最多可讀取多少個(gè)字符。
方法writelines:接受一個(gè)字符串列表(實(shí)際上,可以是任何序列或可迭代對(duì)象),并將這些字符串都寫(xiě)入到文件(或流)中。
寫(xiě)入時(shí)不會(huì)添加換行符,因此你必須自行添加。另外,沒(méi)有方法writeline,因?yàn)榭梢允褂脀rite。
關(guān)閉文件
方法close將文件關(guān)閉
在python中運(yùn)行的而結(jié)果會(huì)存入到緩沖區(qū)中,有可能沒(méi)有將結(jié)果給你進(jìn)行立即返回,通常程序退出時(shí)將自動(dòng)關(guān)閉文件對(duì)象,并將緩沖器的內(nèi)容給返回。當(dāng)然如果不想關(guān)閉文件,又想將緩沖器的內(nèi)容及時(shí)得到,可以使用flush方法。
當(dāng)然也可以使用try/finally語(yǔ)句,并在finally子句中調(diào)用close。
import io f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt','w') try:f.write('like wsq') finally:f.close()有一條專門為此設(shè)計(jì)的語(yǔ)句,那就是with語(yǔ)句,這樣是用的最多的方法
import io with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt','w') as f:f.write('like qibao')上下文管理器
with語(yǔ)句實(shí)際上是一個(gè)非常通用的結(jié)構(gòu),允許你使用所謂的上下文管理器。
上下文管理器是支持兩個(gè)方法的對(duì)象:__enter__和__exit__。
方法__enter__不接受任何參數(shù),在進(jìn)入with語(yǔ)句時(shí)被調(diào)用,其返回值被賦給關(guān)鍵字as后面的變量。
方法__exit__接受三個(gè)參數(shù):異常類型、異常對(duì)象和異常跟蹤。它在離開(kāi)方法時(shí)被調(diào)用(通過(guò)前述參數(shù)將引發(fā)的異常提供給它)。如果__exit__返回False,將抑制所有的異常.
使用文件的基本方法
beyond.txt內(nèi)容如下:
Yellow Skies, I can see the Yellow Skies. See you again, I see you again In my dreams, in my dreams, in my dreams, in my dreams. Morning light, I remember morning light. Outside my doors, I ll see you no more. In my dreams, in my dreams, in my dreams, in my dreams Forever, Forever Ill be forever holding you. Forever, Forever Ill be forever holding you. Responsible, Responsible, Responsible, Responsible. So black and white, Its become so black and white.
read(n)
read()
import io f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') print(f.read())#結(jié)果為: ''' Yellow Skies, I can see the Yellow Skies. See you again, I see you again In my dreams, in my dreams, in my dreams, in my dreams. Morning light, I remember morning light. Outside my doors, I ll see you no more. In my dreams, in my dreams, in my dreams, in my dreams Forever, Forever Ill be forever holding you. Forever, Forever Ill be forever holding you. Responsible, Responsible, Responsible, Responsible. So black and white, Its become so black and white. ''' f.close()readline()
import io f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') for i in range(3):print(str(i)+':'+f.readline(),end='')#結(jié)果為: ''' 0:Yellow Skies, I can see the Yellow Skies. 1:See you again, I see you again 2:In my dreams, in my dreams, in my dreams, in my dreams. ''' f.close()readlines()
import io import pprint pprint.pprint(open(r'E:\Jupyter_workspace\study\python\book\beyond.txt').readlines())#結(jié)果為: ''' ['Yellow Skies, I can see the Yellow Skies.\n','See you again, I see you again\n','In my dreams, in my dreams, in my dreams, in my dreams.\n','Morning light, I remember morning light.\n','Outside my doors, I ll see you no more.\n','In my dreams, in my dreams, in my dreams, in my dreams\n','Forever, Forever Ill be forever holding you.\n','Forever, Forever Ill be forever holding you.\n','Responsible, Responsible, Responsible, Responsible.\n','So black and white,\n','Its become so black and white.'] ''' #這里利用了文件對(duì)象將被自動(dòng)關(guān)閉這一事實(shí)。write(string)
import io f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt','w') f.write('I\nlike\nwsq\n')#結(jié)果為:11 f.close()writelines(list)
import io f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') lines = f.readlines() f.close() lines[1] = "am\n" f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt', 'w') f.writelines(lines) f.close()迭代文件內(nèi)容
使用read遍歷字符
以不同的方式編寫(xiě)循環(huán)
import io def beyond(string):print("words is:",string)with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') as f:while True:char = f.read(1)if not char:breakbeyond(char)''' words is: I words is: words is: a words is: m words is: words is: w words is: s words is: q words is: '''每次一行
處理文本文件時(shí),通常想做的是迭代其中的行,而不是每個(gè)字符。
方法readline,可像迭代字符一樣輕松地迭代行。
在while循環(huán)中使用readline
import io def beyond(string):print("words is:",string)with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') as f:while True:line = f.readline()if not line:breakbeyond(line)''' words is: Iwords is: amwords is: wsq '''讀取所有內(nèi)容
使用read迭代字符
import io def beyond(string):print("words is:",string)with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') as f:for char in f.read():beyond(char) ''' words is: I words is: words is: a words is: m words is: words is: w words is: s words is: q words is: '''使用readlines迭代行
import io def beyond(string):print("words is:",string)with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') as f:for line in f.readlines():beyond(line)''' words is: Iwords is: amwords is: wsq '''使用fileinput實(shí)現(xiàn)延遲行迭代
有時(shí)候需要迭代大型文件中的行,此時(shí)使用readlines將占用太多內(nèi)存。
在Python中,在可能的情況下,應(yīng)首選for循環(huán)。
可使用一種名為延遲行迭代的方法——說(shuō)它延遲是因?yàn)樗蛔x取實(shí)際需要的文本部分。
使用fileinput迭代行
import fileinput import io def beyond(string):print("words is:",string)for line in fileinput.input(r'E:\Jupyter_workspace\study\python\book\beyond.txt'):beyond(line) ''' words is: Iwords is: amwords is: wsq '''文件迭代器
迭代文件
import io def beyond(string):print("words is:",string)with open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') as f:for line in f:beyond(line)''' words is: Iwords is: amwords is: wsq '''在不將文件對(duì)象賦給變量的情況下迭代文件
import io def beyond(string):print("words is:",string)for line in open(r'E:\Jupyter_workspace\study\python\book\beyond.txt'):beyond(line) ''' words is: Iwords is: amwords is: wsq '''與其他文件一樣,sys.stdin也是可迭代的
import sys import io def beyond(string):print("words is:",string)for line in sys.stdin:beyond(line)對(duì)迭代器做的事情基本上都可對(duì)文件做
f = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt', 'w') print('First', 'line', file=f) print('Second', 'line', file=f) print('Third', 'and final', 'line', file=f) f.close() lines = list(open(r'E:\Jupyter_workspace\study\python\book\beyond.txt')) lines#結(jié)果為:['First line\n', 'Second line\n', 'Third and final line\n']first, second, third = open(r'E:\Jupyter_workspace\study\python\book\beyond.txt') first#結(jié)果為:'First line\n' second#結(jié)果為:'Second line\n' third#結(jié)果為:'Third and final line\n'
注意:
1,使用了print來(lái)寫(xiě)入文件,這將自動(dòng)在提供的字符串后面添加換行符。
2,對(duì)打開(kāi)的文件進(jìn)行序列解包,從而將每行存儲(chǔ)到不同的變量中。
3,寫(xiě)入文件后將其關(guān)閉,以確保數(shù)據(jù)得以寫(xiě)入磁盤。
小結(jié)
| 類似于文件的對(duì)象 | 類似于文件的對(duì)象是支持read和readline(可能還有write和writelines)等方法的對(duì)象。 |
| 打開(kāi)和關(guān)閉文件 | 要打開(kāi)文件,可使用函數(shù)open,并向它提供一個(gè)文件名。如果要確保即便發(fā)生錯(cuò)誤時(shí)文件也將被關(guān)閉,可使用with語(yǔ)句。 |
| 模式和文件類型 | 打開(kāi)文件時(shí),還可指定模式,如’r’(讀取模式)或’w’(寫(xiě)入模式)通過(guò)在模式后面加上’b’,可將文件作為二進(jìn)制文件打開(kāi),并關(guān)閉Unicode編碼和換行符替換。 |
| 標(biāo)準(zhǔn)流 | 三個(gè)標(biāo)準(zhǔn)流(模塊sys中的stdin、stdout和stderr)都是類似于文件的對(duì)象,它們實(shí)現(xiàn)了UNIX標(biāo)準(zhǔn)I/O機(jī)制(Windows也提供了這種機(jī)制)。 |
| 讀取和寫(xiě)入 | 要從文件或類似于文件的對(duì)象中讀取,可使用方法read;要執(zhí)行寫(xiě)入操作,可使用方法write。 |
| 讀取和寫(xiě)入行 | 要從文件中讀取行,可使用readline和readlines;要寫(xiě)入行,可使用writelines。 |
| 迭代文件內(nèi)容 | 迭代文件內(nèi)容的方法很多,其中最常見(jiàn)的是迭代文本文件中的行,這可通過(guò)簡(jiǎn)單地對(duì)文件本身進(jìn)行迭代來(lái)做到。還有其他與較舊Python版本兼容的方法,如使用readlines。 |
本章介紹的新函數(shù)
| open(name, …) | 打開(kāi)文件并返回一個(gè)文件對(duì)象 |
總結(jié)
- 上一篇: 红岩下的追捕剧情介绍
- 下一篇: 第十二章 图形用户界面