我要删除该行和接下来的4行。这是我的代码:
bind = open('/etc/bind/named.conf.local','r')
a = dict['name']
for line in bind:
if a in line:
print('line exist')
''' and delete this line and 4 line after it'''
else:
print('line does not exist')
我想将修改文本保存在/etc/bind/named.conf.local中,而无需输入文件。我不想跳过 4行,我希望将其从文件中删除。我不想再次阅读并跳过4行。
我该怎么办?
答案 0 :(得分:2)
我认为以下代码可以满足您的需求。您将必须根据需要调整设置filename
,keyword
和delete
。每当在一行中找到delete
时,该代码将从文件filename
中删除keyword
行。 (包括keyword
行。)
# Settings
filename = "test.txt"
keyword = "def"
delete = 2
# Read lines from file
with open(filename) as f:
lines = f.readlines()
# Process lines
for i, line in enumerate(lines):
if keyword in line:
del lines[i:i + delete]
# Save modified lines to file
with open(filename, "w") as f:
f.writelines(lines)
示例test.txt
之前:
abc
def
ghi
jkl
之后是示例test.txt
:
abc
jkl
答案 1 :(得分:0)
所有这些归结为保留您在匹配行的第一次出现时初始化并随后增加的跳过计数:
match = "text line to match"
with open('input.txt','r') as lines:
with open('output.txt','w') as output:
skip = -1
for line in lines:
skip += skip >= 0 or skip < 0 and line.strip("\n") == match
if skip not in range(5):
output.write(line)
如果您要避免的是逐行阅读,则可以这样写(但是您仍然需要打开文件)
match = "text line to match"
lines = open('input.txt','r').read().split("\n")
matchPos = lines.index(match)
del lines[matchPos:matchPos+5]
open('output.txt','w').write("\n".join(lines))
答案 2 :(得分:0)
如果您不想使用fileinput
,还可以读取文件的所有行,并将它们(使用next(f)
跳过的行除外)写入{{3} }并将原始文件替换为临时文件。
from pathlib import Path
from tempfile import NamedTemporaryFile
named_conf = Path('/etc/bind/named.conf.local')
with open(named_conf) as infile:
with NamedTemporaryFile("w", delete=False) as outfile:
for line in infile:
if line_should_be_deleted(line):
# skip this line and the 4 lines after it
for _ in range(4):
next(infile)
else:
outfile.write(line)
Path(outfile.name).replace(named_conf)
但是您应该只使用fileinput
,就像您链接到的问题的答案一样,因为它可以为您提供临时文件。
答案 3 :(得分:-3)
bind = open('text.txt','r')
a = dict['name']
lines = bind.readlines()
i = 0
while i < len(lines):
if a in lines[i]:
del lines[i:i+5]
i += 1
print(lines)
答案 4 :(得分:-4)
bind = open('/etc/bind/named.conf.local','r')
textfile = bind.readlines()
a = 'some text'
for line_num in range(len(textfile)):
try:
if a in textfile[line_num]:
print('line exists')
del textfile[line_num:line_num+5]
except IndexError:
break
writer = open("/etc/bind/named.conf.local","w")
writer.write(''.join(textfile))
writer.close()