1、文件的打開和建立node
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhello world!\n' >>> f <open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>
2、文件的讀取python
步驟:打開 -- 讀取 -- 關閉正則表達式
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhello world!\n' >>> f.close()
3、文件寫入(慎重,當心別清空本來的文件)緩存
直接的寫入數據是不行的,由於默認打開的是'r' 只讀模式app
>>> 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>
應該先指定可寫的模式ide
>>> f1 = open('/tmp/test.txt','w') >>> f1.write('hello boy!')
但此時數據只寫到了緩存中,並未保存到文件,並且從下面的輸出能夠看到,原先裏面的配置被清空了ui
[root@node1 ~]# cat /tmp/test.txt [root@node1 ~]#
關閉這個文件便可將緩存中的數據寫入到文件中spa
>>> f1.close() [root@node1 ~]# cat /tmp/test.txt [root@node1 ~]# hello boy!
>>> f2 = open('/tmp/test.txt','r+') >>> f2.write('\nhello aa!') >>> f2.close() [root@node1 python]# cat /tmp/test.txt hello aay!
如何實現不替換?指針
>>> 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!
能夠看到,若是在寫以前先讀取一下文件,再進行寫入,則寫入的數據會添加到文件末尾而不會替換掉原先的文件。這是由於指針引發的,r+ 模式的指針默認是在文件的開頭,若是直接寫入,則會覆蓋源文件,經過read() 讀取文件後,指針會移到文件的末尾,再寫入數據就不會有問題了。這裏也能夠使用a 模式orm
>>> 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!
關於其餘模式的介紹,見下表:
模式 |
描述 |
r |
以讀方式打開文件,可讀取文件信息。 |
w |
以寫方式打開文件,可向文件寫入信息。如文件存在,則清空該文件,再寫入新內容 |
a |
以追加模式打開文件(即一打開文件,文件指針自動移到文件末尾),若是文件不存在則建立 |
r+ |
以讀寫方式打開文件,可對文件進行讀和寫操做。 |
w+ |
消除文件內容,而後以讀寫方式打開文件。 |
a+ |
以讀寫方式打開文件,並把文件指針移到文件尾。 |
b |
以二進制模式打開文件,而不是以文本模式。該模式只對Windows或Dos有效,類Unix的文件是用二進制模式進行操做的。 |
>>> 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.txt hello 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()
選項=0,表示將文件指針指向從文件頭部到「偏移量」字節處
選項=1,表示將文件指針指向從文件的當前位置,向後移動「偏移量」字節
選項=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
4、內容查找和替換
1、內容查找
實例:統計文件中hello個數
思路:打開文件,遍歷文件內容,經過正則表達式匹配關鍵字,統計匹配個數。
[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
#!/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!
實例:讀取文件test.txt內容,去除空行和註釋行後,以行爲單位進行排序,並將結果輸出爲result.txt。test.txt 的內容以下所示:
#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(): # 逐行讀取數據 line = line.strip() #去掉每行頭尾空白 if not len(line) or line.startswith('#'): # 判斷是不是空行或註釋行 continue #是的話,跳過不處理 result.append(line) #保存 result.sort() #排序結果 print result open('cdays-4-result.txt','w').write('%s' % '\n'.join(result)) #保存入結果文件