Python讀寫txt文本文件的操作方法全解析
一、文件的打開和創(chuàng)建
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhello world!\n' >>> f <open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>
二、文件的讀取
步驟:打開 -- 讀取 -- 關(guān)閉
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhello world!\n' >>> f.close()
讀取數(shù)據(jù)是后期數(shù)據(jù)處理的必要步驟。.txt是廣泛使用的數(shù)據(jù)文件格式。一些.csv, .xlsx等文件可以轉(zhuǎn)換為.txt 文件進(jìn)行讀取。我常使用的是Python自帶的I/O接口,將數(shù)據(jù)讀取進(jìn)來存放在list中,然后再用numpy科學(xué)計(jì)算包將list的數(shù)據(jù)轉(zhuǎn)換為array格式,從而可以像MATLAB一樣進(jìn)行科學(xué)計(jì)算。
下面是一段常用的讀取txt文件代碼,可以用在大多數(shù)的txt文件讀取中
filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt文件和當(dāng)前腳本在同一目錄下,所以不用寫具體路徑 pos = [] Efield = [] with open(filename, 'r') as file_to_read: while True: lines = file_to_read.readline() # 整行讀取數(shù)據(jù) if not lines: break pass p_tmp, E_tmp = [float(i) for i in lines.split()] # 將整行數(shù)據(jù)分割處理,如果分割符是空格,括號里就不用傳入?yún)?shù),如果是逗號, 則傳入‘,'字符。 pos.append(p_tmp) # 添加新讀取的數(shù)據(jù) Efield.append(E_tmp) pass pos = np.array(pos) # 將數(shù)據(jù)從list類型轉(zhuǎn)換為array類型。 Efield = np.array(Efield) pass
例如下面是將要讀入的txt文件
經(jīng)過讀取后,在Enthought Canopy的variable window查看讀入的數(shù)據(jù), 左側(cè)為pos,右側(cè)為Efield。
三、文件寫入(慎重,小心別清空原本的文件)
步驟:打開 -- 寫入 -- (保存)關(guān)閉
直接的寫入數(shù)據(jù)是不行的,因?yàn)槟J(rèn)打開的是'r' 只讀模式
>>> f.write('hello boy') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: File not open for writing >>> f <open file '/tmp/test.txt', mode 'r' at 0x7fe550a49d20>
應(yīng)該先指定可寫的模式
>>> f1 = open('/tmp/test.txt','w') >>> f1.write('hello boy!')
但此時(shí)數(shù)據(jù)只寫到了緩存中,并未保存到文件,而且從下面的輸出可以看到,原先里面的配置被清空了
[root@node1 ~]# cat /tmp/test.txt [root@node1 ~]#
關(guān)閉這個(gè)文件即可將緩存中的數(shù)據(jù)寫入到文件中
>>> f1.close() [root@node1 ~]# cat /tmp/test.txt [root@node1 ~]# hello boy!
注意:這一步需要相當(dāng)慎重,因?yàn)槿绻庉嫷奈募嬖诘脑?,這一步操作會先清空這個(gè)文件再重新寫入。那么如果不要清空文件再寫入該如何做呢?
使用r+ 模式不會先清空,但是會替換掉原先的文件,如下面的例子:hello boy! 被替換成hello aay!
>>> f2 = open('/tmp/test.txt','r+') >>> f2.write('\nhello aa!') >>> f2.close() [root@node1 python]# cat /tmp/test.txt hello aay!
如何實(shí)現(xiàn)不替換?
>>> f2 = open('/tmp/test.txt','r+') >>> f2.read() 'hello girl!' >>> f2.write('\nhello boy!') >>> f2.close() [root@node1 python]# cat /tmp/test.txt hello girl! hello boy!
可以看到,如果在寫之前先讀取一下文件,再進(jìn)行寫入,則寫入的數(shù)據(jù)會添加到文件末尾而不會替換掉原先的文件。這是因?yàn)橹羔樢鸬?,r+ 模式的指針默認(rèn)是在文件的開頭,如果直接寫入,則會覆蓋源文件,通過read() 讀取文件后,指針會移到文件的末尾,再寫入數(shù)據(jù)就不會有問題了。這里也可以使用a 模式
>>> f = open('/tmp/test.txt','a') >>> f.write('\nhello man!') >>> f.close() >>> [root@node1 python]# cat /tmp/test.txt hello girl! hello boy! hello man!
關(guān)于其他模式的介紹,見下表:
文件對象的方法:
f.readline() 逐行讀取數(shù)據(jù)
方法一:
>>> f = open('/tmp/test.txt') >>> f.readline() 'hello girl!\n' >>> f.readline() 'hello boy!\n' >>> f.readline() 'hello man!' >>> f.readline() ''
方法二:
>>> for i in open('/tmp/test.txt'): ... print i ... hello girl! hello boy! hello man! f.readlines() 將文件內(nèi)容以列表的形式存放 >>> f = open('/tmp/test.txt') >>> f.readlines() ['hello girl!\n', 'hello boy!\n', 'hello man!'] >>> f.close()
f.next() 逐行讀取數(shù)據(jù),和f.readline() 相似,唯一不同的是,f.readline() 讀取到最后如果沒有數(shù)據(jù)會返回空,而f.next() 沒讀取到數(shù)據(jù)則會報(bào)錯(cuò)
>>> f = open('/tmp/test.txt') >>> f.readlines() ['hello girl!\n', 'hello boy!\n', 'hello man!'] >>> f.close() >>> >>> f = open('/tmp/test.txt') >>> f.next() 'hello girl!\n' >>> f.next() 'hello boy!\n' >>> f.next() 'hello man!' >>> f.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
f.writelines() 多行寫入
>>> l = ['\nhello dear!','\nhello son!','\nhello baby!\n'] >>> f = open('/tmp/test.txt','a') >>> f.writelines(l) >>> f.close() [root@node1 python]# cat /tmp/test.txt hello girl! hello boy! hello man! hello dear! hello son! hello baby!
f.seek(偏移量,選項(xiàng))
>>> f = open('/tmp/test.txt','r+') >>> f.readline() 'hello girl!\n' >>> f.readline() 'hello boy!\n' >>> f.readline() 'hello man!\n' >>> f.readline() ' ' >>> f.close() >>> f = open('/tmp/test.txt','r+') >>> f.read() 'hello girl!\nhello boy!\nhello man!\n' >>> f.readline() '' >>> f.close()
這個(gè)例子可以充分的解釋前面使用r+這個(gè)模式的時(shí)候,為什么需要執(zhí)行f.read()之后才能正常插入
f.seek(偏移量,選項(xiàng))
(1)選項(xiàng)=0,表示將文件指針指向從文件頭部到“偏移量”字節(jié)處
(2)選項(xiàng)=1,表示將文件指針指向從文件的當(dāng)前位置,向后移動“偏移量”字節(jié)
(3)選項(xiàng)=2,表示將文件指針指向從文件的尾部,向前移動“偏移量”字節(jié)
偏移量:正數(shù)表示向右偏移,負(fù)數(shù)表示向左偏移
>>> f = open('/tmp/test.txt','r+') >>> f.seek(0,2) >>> f.readline() '' >>> f.seek(0,0) >>> f.readline() 'hello girl!\n' >>> f.readline() 'hello boy!\n' >>> f.readline() 'hello man!\n' >>> f.readline() ''
f.flush() 將修改寫入到文件中(無需關(guān)閉文件)
>>> f.write('hello python!') >>> f.flush()
[root@node1 python]# cat /tmp/test.txt
hello girl! hello boy! hello man! hello python!
f.tell() 獲取指針位置
>>> f = open('/tmp/test.txt') >>> f.readline() 'hello girl!\n' >>> f.tell() 12 >>> f.readline() 'hello boy!\n' >>> f.tell() 23
四、內(nèi)容查找和替換
1、內(nèi)容查找
實(shí)例:統(tǒng)計(jì)文件中hello個(gè)數(shù)
思路:打開文件,遍歷文件內(nèi)容,通過正則表達(dá)式匹配關(guān)鍵字,統(tǒng)計(jì)匹配個(gè)數(shù)。
[root@node1 ~]# cat /tmp/test.txt
hello girl! hello boy! hello man! hello python!
腳本如下:
方法一:
#!/usr/bin/python import re f = open('/tmp/test.txt') source = f.read() f.close() r = r'hello' s = len(re.findall(r,source)) print s [root@node1 python]# python count.py 4
方法二:
#!/usr/bin/python import re fp = file("/tmp/test.txt",'r') count = 0 for s in fp.readlines(): li = re.findall("hello",s) if len(li)>0: count = count + len(li) print "Search",count, "hello" fp.close() [root@node1 python]# python count1.py Search 4 hello
2、替換
實(shí)例:把test.txt 中的hello全部換為"hi",并把結(jié)果保存到myhello.txt中。
#!/usr/bin/python import re f1 = open('/tmp/test.txt') f2 = open('/tmp/myhello.txt','r+') for s in f1.readlines(): f2.write(s.replace('hello','hi')) f1.close() f2.close() [root@node1 python]# touch /tmp/myhello.txt [root@node1 ~]# cat /tmp/myhello.txt hi girl! hi boy! hi man! hi python!
實(shí)例:讀取文件test.txt內(nèi)容,去除空行和注釋行后,以行為單位進(jìn)行排序,并將結(jié)果輸出為result.txt。test.txt 的內(nèi)容如下所示:
#some words Sometimes in life, You find a special friend; Someone who changes your life just by being part of it. Someone who makes you laugh until you can't stop; Someone who makes you believe that there really is good in the world. Someone who convinces you that there really is an unlocked door just waiting for you to open it. This is Forever Friendship. when you're down, and the world seems dark and empty, Your forever friend lifts you up in spirits and makes that dark and empty world suddenly seem bright and full. Your forever friend gets you through the hard times,the sad times,and the confused times. If you turn and walk away, Your forever friend follows, If you lose you way, Your forever friend guides you and cheers you on. Your forever friend holds your hand and tells you that everything is going to be okay.
腳本如下:
f = open('cdays-4-test.txt') result = list() for line in f.readlines(): # 逐行讀取數(shù)據(jù) line = line.strip() #去掉每行頭尾空白 if not len(line) or line.startswith('#'): # 判斷是否是空行或注釋行 continue #是的話,跳過不處理 result.append(line) #保存 result.sort() #排序結(jié)果 print result open('cdays-4-result.txt','w').write('%s' % '\n'.join(result)) #保存入結(jié)果文件
相關(guān)文章
python?使用第三方庫requests-toolbelt?上傳文件流的示例
這篇文章主要介紹了python?使用第三方庫requests-toolbelt?上傳文件流,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09python項(xiàng)目下生成requirements.txt方法
這篇文章主要介紹了python項(xiàng)目下生成requirements.txt的方法,很多小伙伴不知道如何生成requirements.txt,本文就通過代碼示例給大家詳細(xì)介紹如何生成,,需要的朋友可以參考下2023-06-06Python+OpenCV圖像處理——實(shí)現(xiàn)輪廓發(fā)現(xiàn)
這篇文章主要介紹了Python+OpenCV實(shí)現(xiàn)輪廓發(fā)現(xiàn),幫助大家更好的利用python處理圖片,感興趣的朋友可以了解下2020-10-10Python面試之os.system()和os.popen()的區(qū)別詳析
Python調(diào)用Shell,有兩種方法:os.system(cmd)或os.popen(cmd)腳本執(zhí)行過程中的輸出內(nèi)容,下面這篇文章主要給大家介紹了關(guān)于Python面試之os.system()和os.popen()區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-06-06python使用requests模塊實(shí)現(xiàn)爬取電影天堂最新電影信息
這篇文章主要介紹了python使用requests模塊實(shí)現(xiàn)爬取電影天堂最新電影信息,本文通過實(shí)例代碼給大家介紹了str/list/tuple三者之間怎么相互轉(zhuǎn)換,需要的朋友可以參考下2019-04-04Python面向?qū)ο缶幊讨庋b的藝術(shù)你了解嗎
這篇文章主要為大家詳細(xì)介紹了Python面向?qū)ο缶幊讨庋b的藝術(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02