<p>老实说,我不明白上面的例子。我不停地摸索,得出了以下结论:我创建了一个列表,其中填充了搜索代码的输出。然后我想写每一行不等于我的索引。我很困惑</p>
<pre><code>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();
</code></pre>
<p>我还尝试创建一个元素列表,然后尝试使用del删除这些元素,但我一直遇到一个错误</p>
<pre><code>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();
</code></pre>
<p>我得到的错误</p>
<pre><code>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
</code></pre>
<p>但是type返回int,所以我不明白我在做什么。你知道吗</p>