Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于serach conditon python删除多行_Python - Fatal编程技术网

基于serach conditon python删除多行

基于serach conditon python删除多行,python,Python,我正在使用DHCP编辑器添加、删除和搜索主机。我有代码可以搜索并添加一个主机,我想我会以某种方式将两者结合起来删除一个主机,但这不起作用。我想做的是创建f.readlines()的元素索引列表,然后使用myindex的值,然后运行行。从我正在编辑的DHCP文件中删除(myindex) 示例我想搜索foonode或任何节点并删除以下格式: host barnode{ option host-name "barnode"; option root-path "0.0.0.0:

我正在使用DHCP编辑器添加、删除和搜索主机。我有代码可以搜索并添加一个主机,我想我会以某种方式将两者结合起来删除一个主机,但这不起作用。我想做的是创建
f.readlines()
的元素索引列表,然后使用myindex的值,然后运行
行。从我正在编辑的DHCP文件中删除(myindex)

示例我想搜索
foonode
或任何节点并删除以下格式:

    host barnode{
    option host-name "barnode";
    option root-path "0.0.0.0:/barnode";
    option subnet-mask ;
    option routers ;
    hardware ethernet  ;
    fixed-address ;
}





host foonode{
    option host-name "foonode";
    option root-path "0.0.0.0:/foonode";
    option subnet-mask ;
    option routers ;
    hardware ethernet  ;
    fixed-address ;
}




host foobarnode{
    option host-name "foobarnode";
    option root-path "0.0.0.0:/foobarnode";
    option subnet-mask ;
    option routers ;
    hardware ethernet ;
    fixed-address ;
}
我可以使用以下代码搜索该文件:

def delete_host():

    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    myfile=str()
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()
    for line in lines:
            if re.search(host, line):
                    start = True

            if start:
                   print line
                   myindex = [lines.index(line)]   


                    if re.search('}', line):
                            break
并获得以下输出:

    host foonode{

    option host-name "foonode";

    option root-path "0.0.0.0:/foonode";

    option subnet-mask ;

    option routers ;

    hardware ethernet ;

    fixed-address ;
我想为搜索条件中的
f.readlines()
创建元素索引值的索引列表。然后使用这些值执行
lines.remove(myindex.index())
以删除运行上述代码时获得的输出。基本上,我如何搜索任何节点并从文件中删除它们。 也许创建一个索引不是解决这个问题的最好方法,我只是在谷歌上搜索的表达式已经没有了


我知道我必须执行
newfile=open('/var/tmp/foodhcp''w')
,但我希望在开始编写文件之前获得正确的逻辑。

请注意,从正在循环的列表中删除项目不会按预期的方式工作。我建议

a = [1,2,3,4,5]
del a[2:4]
a==[1,2,5]


您已经能够找到起始线和结束线,因此在找到这些线后只需运行del。

如果您已经有线列表,只需从要删除的线之前和之后的零件创建一个新的更新列表:

import re

with open('data.txt') as f:
    s = f.read()

print("Before:")
print(s)

def delete_host(s):
    host = raw_input('Please enter host you would like to delete: ')

    lines = s.split('\n')
    for i, line in enumerate(lines):
        if re.match(r'\s*host\s+' + host + '\s*{', line):
            break

    for j, line in enumerate(lines[i+1:]):
        if re.match(r'\s*}', line):
            break

    j = i + j + 1

    new_lines = lines[:i] + lines[j+1:]
    return '\n'.join(new_lines)

s = delete_host(s)
print("After:")
print(s)
(请注意,检查缺少的主机名、格式不正确或带有可能干扰regexp的有趣符号的主机名时不会出错)

如果您确定所有条目始终与您描述的相似(特别是,
}
不会在
主机
正文中的任何位置遇到),您可以将其简化为

def delete_host(s):
    host = raw_input('Please enter host you would like to delete: ')
    return re.sub(r'\s*host\s+' + host + '\s*{[^}]*}', '', s, flags=re.MULTILINE)

最安全的方法是实际解析配置文件,获取数据结构,删除条目,然后创建新的配置文件

老实说,我不理解上面的例子。我一直在努力工作,并得出以下结论:我创建了一个列表,其中填充了搜索代码的输出。然后我想写每一行不等于myindex的内容。我很困惑

import re
infile='C:\dhcp.txt'
def delete_host():
    infile = 'C:\dhcp.txt'
    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    nf=open(r'C:\test.txt', 'w')
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()

    for i, line in enumerate(lines):
            if re.search(host, line):
                start = True
                if start:
                 myindex.append(line)
                if re.search('}',line):
                    break
    for myindex in lines:
        if lines != myindex:
            mystr.join(lines)
            nf.write(mystr)
            nf.close
delete_host();
我还尝试创建一个元素列表,然后尝试使用del删除这些元素,但我一直遇到错误

def delete_host():
    infile = 'C:\dhcp.txt'
    host=raw_input('Please enter host you would like to delete: ');
    start = False;
    f=open(infile, 'r')
    nf=open(r'C:\test.txt', 'w')
    myfile=str()
    myindex=list()
    mystr=str()
    count = 0
    lines = f.readlines()

    for i, line in enumerate(lines):
            if re.search(host, line):
                start = True

            if start:

                #print line
                #myindex=lines.index(line)

                myindex.append(lines.index(line))
                #myindex.append(line)
                if re.search('}',line):
                    break
    print myindex
    print type(myindex[0])

    del lines[myindex]

delete_host();
我犯了一个错误

Please enter host you would like to delete: rest
[13, 14, 15, 16, 17, 18, 19, 7]
<type 'int'>

Traceback (most recent call last):
  File "C:\delete.py", line 52, in <module>
    delete_host();
  File "C:\delete.py", line 35, in delete_host
    del lines[myindex]
TypeError: list indices must be integers, not list
请输入要删除的主机:rest
[13, 14, 15, 16, 17, 18, 19, 7]
回溯(最近一次呼叫最后一次):
文件“C:\delete.py”,第52行,在
删除主机();
文件“C:\delete.py”,第35行,在delete\u主机中
删除行[myindex]
TypeError:列表索引必须是整数,而不是列表

但是type返回int,所以我不明白我在做什么

如果其他人也有同样的问题,我最终解决了这个问题。谈谈接吻在行动中的原则。感谢所有回应的人。如果搜索条件为true,以下代码将从dhcpd.conf文件中删除主机

    def delete_host():

        host=raw_input('Please enter host you would like to delete: ');
        start = False;
        infile= '/etc/dhcp/dhcpd.conf'
        f=open(infile, 'r')
        lines = f.readlines()
        nf = open('/var/tmp/testing','w')

        for line in lines:
                if re.search(host, line):
                        print 'if search'
                        start = True
                if start:
                        print 'is start'
                        print line
                        if re.search('}', line):
                                start = False
                                print 'false'
                else:

                        nf.write(line)
                        print 'writing'


delete_host()