Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 391
Chris Jones Avatar asked Apr 12 '26 11:04

Chris Jones


1 Answers

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.

like image 186
roippi Avatar answered Apr 15 '26 00:04

roippi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!