简体   繁体   中英

How can I delete multipe lines in a text by Python?

I have a similar question to delete multiple line

I want to delete the line and the next 4 lines. This is my code:

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')

I want to save modify text in /etc/bind/named.conf.local in place, without fileinput. I do not want skip 4 line I want to delete them from the file. I do not want to read it and write it again and skip 4 lines.

What should I do?

I think the following code does what you're looking for. You will have to adjust settings filename , keyword and delete to your needs. The code will delete delete lines from file filename every time keyword is found in a line. (Including the keyword line.)

# 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)

Example test.txt before:

abc
def
ghi
jkl

Example test.txt afterwards:

abc
jkl

It all boils down to keeping a skip count that you initialize with the first occurrence of the matching line and increase afterward:

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)

If what you're trying to avoid is reading lines one by one, you could write it like this (but you still need to open the files)

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))

If you don't want to use fileinput , you can also read all the lines of your file, write them (except for the lines you skip using next(f) ) to a tempfile.NamedTemporaryFile and replace the original file with the temporary file.

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)

But you should just use fileinput , like the answer to the question you linked to says, since it does the tempfile stuff for you.

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)
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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM