Python修改文本指定行
首先我是初学者,没有找到类似于linux sed替换命令的方法,主要逻辑是读取文件,清空文件,将修改之后的内容再写进去。这种方法问题很多,例如同时操作文件或者文件过大。这只是一种方法。
全文修改:
[admin@pe-jira python]$ cat ming.txt qqqqqqqqqq:qqqqqqqq:0 99999999999:123456789:0 111:111:11111111 >>> f = open('ming.txt','r+') >>> a = f.readlines() >>> f = open('ming.txt','w') >>> for i in a: ... f.write(i.replace('wangxu','--------------')) ... 22 17 26 27 >>> f.close() >>> [admin@pe-jira python]$ cat ming.txt qqqqqqqqqq:qqqqqqqq:0 111:111:11111111 --------------:222:222222 --------------01:333:33333
修改指定行
[admin@pe-jira python]$ cat ming.txt 1:111:111 1:22222:222 3:33333:222 >>> f = open('ming.txt','r') >>> a = f.readlines() >>> f = open('ming.txt','w') >>> for i in a: ... f.write(i.replace('1:111:111','9:999:999')) ... 10 12 12 >>> f.close() >>> [admin@pe-jira python]$ cat ming.txt 9:999:999 1:22222:222 3:33333:222
re正则全文替换
[admin@pe-jira python]$ cat ming.txt 9:999:9998 3:33333:2 0:999:99999 >>> f = open('ming.txt','r') >>> a = f.read() >>> import re >>> s = re.sub(r"999",'--------',a) >>> f = open('ming.txt','w') >>> f.write(s) 53 >>> s '9:--------:--------8\n3:33333:2\n0:--------:--------99\n' >>> 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 >>> f = open('ming.txt','r') >>> a = f.read() >>> import re >>> s = re.sub(r"999",'--------',a,1) >>> f = open('ming.txt','w') >>> f.write(s) 38 >>> f.close() >>> [admin@pe-jira python]$ cat ming.txt 9:--------:9998 3:33333:2 0:999:99999 [admin@pe-jira python]$