python 删除特定字符所在行

#查询文件中含有特殊字符串的行

#!/usr/bin/python
# -*- coding:utf-8 -*-
import re
file1 = open('test.txt','r+')
istxt = re.compile(r'.*if.*',re.I)
for line in file1.readlines():
   line = line.strip()
   ifstr = re.findall(istxt,line)
   if ifstr:
    print ifstr


#删除特定行(创建新文件,把不含字符的那些行写进新文件中,重命名文件成原来的文件名称)

#!/usr/bin/python
# -*- coding:utf-8 -*-
import re
import os
file1 = open('test.txt','r+')
new_file = 'new_test.txt'

if not os.path.exists(new_file):
    os.system(r"touch {}".format(new_file))
file2 = open('new_test.txt','r+')
istxt = re.compile(r'.*if.*',re.I)
for line in file1.readlines():
   line = line.strip()
   ifstr = re.findall(istxt,line)
   if ifstr:
     line = []
   else:
     file2.write(line  + '\n')

file1.close()
file2.close()
#重命名文件
os.rename("new_test.txt","test.txt")

暂时想到这个思路,不知道还有其他思路没有 ?

 

posted @ 2019-08-19 19:17  醉城、  阅读(8816)  评论(0编辑  收藏  举报