Python删除文本指定字符/行

首先我是初学者,没有找到类似于linux sed替换或者删除一行命令的方法,主要逻辑是读取文件,清空文件,将修改之后的内容再写进去。这种方法问题很多,例如同时操作文件或者文件过大。这只是一种方法。

全文删除:

[admin@pe-jira python]$ cat ming.txt 
9:999:999
1:22222:222
3:33333:222
0:999:999

>>> f = open('ming.txt','r')    
>>> a = f.readlines()
>>> f = open('ming.txt','w')     
>>> for i in a:                   
...     f.write(i.replace("22",""))
... 
10
6
10
10
>>> f.close()

[admin@pe-jira python]$ cat ming.txt 
9:999:999
1:2:2
3:33333:2
0:999:999
[admin@pe-jira python]$	

删除匹配开头行

[admin@pe-jira python]$ cat ming.txt 
9:999:999
1:2:2
3:33333:2
0:999:999
>>> f = open('ming.txt','r')   
>>> a = f.readlines()                         
>>> f = open('ming.txt','w')   
>>> for i in a:
...     if i.startswith('9'):
...             pass
...     else:
...             f.write(i)
... 
6
10
10
>>> f.close()
>>>
[admin@pe-jira python]$ cat ming.txt 
1:2:2
3:33333:2
0:999:999
[admin@pe-jira python]$

re正则全文删除

[admin@pe-jira python]$  cat ming.txt        
9:999:9998
3:33333:2
0:999:99999
>>> import re
>>> s = re.sub(r"999",'',a)
>>> s
'9::\n3:33333:2\n0::\n'
>>> f = open('ming.txt','w')
>>> f.write(s)
18
>>> f.close()
>>> import re
>>> f = open('ming.txt','r')
>>> a = f.read()
>>> s = re.sub(r"999",'',a)
>>> f = open('ming.txt','w')
>>> f.write(s)              
21
>>> f.close()               
>>>


[admin@pe-jira python]$  cat ming.txt 
9::8
3:33333:2
0::99
[admin@pe-jira python]$

re正则只删除第一个匹配的

[admin@pe-jira python]$  cat ming.txt        
9:999:9998
3:33333:2
0:999:99999

>>> import re
>>> f = open('ming.txt','r')
>>> a = f.read()            
>>> s = re.sub(r"999",'',a,1)
>>> s
'9::9998\n3:33333:2\n0:999:99999\n'
>>> f = open('ming.txt','w') 
>>> f.write(s)               
30
>>> f.close()                
>>>
[admin@pe-jira python]$  cat ming.txt 
9::9998
3:33333:2
0:999:99999
[admin@pe-jira python]$

 

posted on 2017-05-27 15:30  光阴8023  阅读(5265)  评论(0编辑  收藏  举报