Python讀寫txt文字檔的操作方法全解析,
一、檔案的開啟和建立
>>> f = open('/tmp/test.txt')>>> f.read()'hello python!\nhello world!\n'>>> f<open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>
二、檔案的讀取
步驟:開啟 -- 讀取 -- 關閉
>>> f = open('/tmp/test.txt')>>> f.read()'hello python!\nhello world!\n'>>> f.close()
讀取資料是後期資料處理的必要步驟。.txt是廣泛使用的資料檔案格式。一些.csv, .xlsx等檔案可以轉換為.txt 檔案進行讀取。我常使用的是Python內建的I/O介面,將資料讀取進來存放在list中,然後再用numpy科學計算包將list的資料轉換為array格式,從而可以像MATLAB一樣進行科學計算。
下面是一段常用的讀取txt檔案代碼,可以用在大多數的txt檔案讀取中
filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt檔案和當前指令碼在同一目錄下,所以不用寫具體路徑pos = []Efield = []with open(filename, 'r') as file_to_read: while True: lines = file_to_read.readline() # 整行讀取資料 if not lines: break pass p_tmp, E_tmp = [float(i) for i in lines.split()] # 將整行資料分割處理,如果分割符是空格,括弧裡就不用傳入參數,如果是逗號, 則傳入‘,'字元。 pos.append(p_tmp) # 添加新讀取的資料 Efield.append(E_tmp) pass pos = np.array(pos) # 將資料從list類型轉換為array類型。 Efield = np.array(Efield) pass
例如下面是將要讀入的txt檔案
經過讀取後,在Enthought Canopy的variable window查看讀入的資料, 左側為pos,右側為Efield。
三、檔案寫入(謹慎,小心別清空原本的檔案)
步驟:開啟 -- 寫入 -- (儲存)關閉
直接的寫入資料是不行的,因為預設開啟的是'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>
應該先指定可寫的模式
>>> f1 = open('/tmp/test.txt','w')>>> f1.write('hello boy!')
但此時資料唯寫到了緩衝中,並未儲存到檔案,而且從下面的輸出可以看到,原先裡面的配置被清空了
[root@node1 ~]# cat /tmp/test.txt[root@node1 ~]#
關閉這個檔案即可將緩衝中的資料寫入到檔案中
>>> f1.close()[root@node1 ~]# cat /tmp/test.txt[root@node1 ~]# hello boy!
注意:這一步需要相當謹慎,因為如果編輯的檔案存在的話,這一步操作會先清空這個檔案再重新寫入。那麼如果不要清空檔案再寫入該如何做呢?
使用r+ 模式不會先清空,但是會替換掉原先的檔案,如下面的例子:hello boy! 被替換成hello aay!
>>> f2 = open('/tmp/test.txt','r+')>>> f2.write('\nhello aa!')>>> f2.close()[root@node1 python]# cat /tmp/test.txthello aay!
如何?不替換?
>>> f2 = open('/tmp/test.txt','r+')>>> f2.read()'hello girl!'>>> f2.write('\nhello boy!')>>> f2.close()[root@node1 python]# cat /tmp/test.txthello girl!hello boy!
可以看到,如果在寫之前先讀取一下檔案,再進行寫入,則寫入的資料會添加到檔案末尾而不會替換掉原先的檔案。這是因為指標引起的,r+ 模式的指標預設是在檔案的開頭,如果直接寫入,則會覆蓋源檔案,通過read() 讀取檔案後,指標會移到檔案的末尾,再寫入資料就不會有問題了。這裡也可以使用a 模式
>>> f = open('/tmp/test.txt','a')>>> f.write('\nhello man!')>>> f.close()>>>[root@node1 python]# cat /tmp/test.txthello girl!hello boy!hello man!
關於其他模式的介紹,見下表:
檔案對象的方法:
f.readline() 逐行讀取資料
方法一:
>>> 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() 將檔案內容以列表的形式存放>>> f = open('/tmp/test.txt')>>> f.readlines()['hello girl!\n', 'hello boy!\n', 'hello man!']>>> f.close()
f.next() 逐行讀取資料,和f.readline() 相似,唯一不同的是,f.readline() 讀取到最後如果沒有資料會返回空,而f.next() 沒讀取到資料則會報錯
>>> 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.txthello girl!hello boy!hello man!hello dear!hello son!hello baby!
f.seek(位移量,選項)
>>> 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()
這個例子可以充分的解釋前面使用r+這個模式的時候,為什麼需要執行f.read()之後才能正常插入
f.seek(位移量,選項)
(1)選項=0,表示將檔案指標指向從檔案頭部到“位移量”位元組處
(2)選項=1,表示將檔案指標指向從檔案的當前位置,向後移動“位移量”位元組
(3)選項=2,表示將檔案指標指向從檔案的尾部,向前移動“位移量”位元組
位移量:正數表示向右位移,負數表示向左位移
>>> 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() 將修改寫入到檔案中(無需關閉檔案)
>>> 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
四、內容尋找和替換
1、內容尋找
執行個體:統計檔案中hello個數
思路:開啟檔案,遍曆檔案內容,通過Regex匹配關鍵字,統計匹配個數。
[root@node1 ~]# cat /tmp/test.txt
hello girl!hello boy!hello man!hello python!
指令碼如下:
方法一:
#!/usr/bin/pythonimport ref = 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.py4
方法二:
#!/usr/bin/pythonimport refp = file("/tmp/test.txt",'r')count = 0for 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.pySearch 4 hello
2、替換
執行個體:把test.txt 中的hello全部換為"hi",並把結果儲存到myhello.txt中。
#!/usr/bin/pythonimport ref1 = 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.txthi girl!hi boy!hi man!hi python!
執行個體:讀取檔案test.txt內容,去除空行和注釋行後,以行為單位進行排序,並將結果輸出為result.txt。test.txt 的內容如下所示:
#some wordsSometimes 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 worldsuddenly 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(): # 逐行讀取資料line = line.strip() #去掉每行頭尾空白if not len(line) or line.startswith('#'): # 判斷是否是空行或注釋行continue #是的話,跳過不處理result.append(line) #儲存result.sort() #排序結果print resultopen('cdays-4-result.txt','w').write('%s' % '\n'.join(result)) #儲存入結果檔案