首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python删除匹配内容行解决方案

2012-05-27 
python删除匹配内容行Python code#-*- coding: cp936 -*-for ip in open(rd:\python_dev\test3.txt).rea

python删除匹配内容行

Python code
#-*- coding: cp936 -*-for ip in open(r'd:\python_dev\test3.txt').read().split('\n'):    print ipa=open(r'd:\python_dev\test.txt',"r").readlines()open(r"D:\python_dev\test.txt","w").write("")for x in a:    if ip in x:        continue    open(r"D:\python_dev\test.txt","a").write(x)


test3.txt的内容如下:
1.1.1.1
2.2.2.2
3.3.3.3

想把test.txt中包含这些内容的行删除

但我现在写这个貌似有问题,无法删除

[解决办法]
Python code
#!/usr/bin/python# encoding: utf-8iplist = set(open(r'test3.txt').read().split('\n'))def ipfilter(ln):    for ip in iplist:        if ip in ln:             return False    else:        return Truetobewrite = filter(ipfilter, open(r'test.txt',"rt"))open(r"test.txt","wt").writelines(tobewrite)'''test3.txt:1.1.1.12.2.2.23.3.3.3test.txt: (before)1.1.1.12.2.2.23.3.3.321.51.1.12.23.12.23.3.53.31.15.1.12.2.2.23.3.31.31.1.1.12.22.2.23.3.3.3test.txt: (after)21.51.1.12.23.12.23.3.53.31.15.1.13.3.31.32.22.2.2'''
[解决办法]
Python code
ifd = open(r'd:\python_dev\test3.txt').read().split("\n")fd = open(r'd:\python_dev\test.txt', 'w').read().split("\n")alist = [ip + "\n" for ip in rfd if ip not in ifd]fd.seek(0,0)fd.writelines(alist) 

热点排行