Chris Jones
Chris Jones

Reputation: 696

How do I delete multiple lines in a text file with python?

I am practicing my python skills by writing a Phone book program. I am able to search and add entries but I am having a lot of trouble deleting entries.

I am trying to find a line that matches my search and delete it as well as the next 4 lines. I have a function to delete here:

def delete():
    del_name = raw_input("What is the first name of the person you would like to delete? ")
    with open("phonebook.txt", "r+") as f:
            deletelines = f.readlines()
            for i, line in enumerate(deletelines):
                if del_name in line:
                    for l in deletelines[i+1:i+4]:
                        f.write(l)

This does not work.

How would I delete multiple entries from a text file like this?

Upvotes: 3

Views: 9160

Answers (1)

roippi
roippi

Reputation: 25954

Answering your direct question: you can use fileinput to easily alter a text file in-place:

import fileinput
file = fileinput.input('phonebook.txt', inplace=True)

for line in file:
     if word_to_find in line:
         for _ in range(4): # skip this line and next 4 lines
             next(file, None)
     else:
         print line,

In order to avoid reading the entire file into memory, this handles some things in the background for you - it moves your original file to a tempfile, writes the new file, and then deletes the tempfile.

Probably better answer: it looks like you have rolled a homemade serialization solution. Consider using a built-in library like csv, json, shelve, or even sqlite3 to persist your data in an easier-to-work-with format.

Upvotes: 1

Related Questions