Hi everybody!

I am currently working on a low level console/text based python phonebook.

I have a working program and i can add and search entries just fine, but what I want to know is...can I remove entries?

I am using the OS package...so i 'import os' at the beginning, have some other code, like

addressbook = "phonebook.dat"

then this:

def WriteEntry_():
name = raw_input(" Enter name: ")
phone = raw_input(" Enter phone number: ")
f=open(addressbook, 'a')
f.write(name + " " + phone + '\n')
f.close()
os.fsync()
print "\n"
print " Added: " + name + " " + phone + " to the phone list.\n"

def DeleteEntry_():
name = raw_input(" Enter name to remove: ")
phone = raw_input(" Enter phone number to remove: ")
f=open(addressbook, 'a')
f.write(name + " " + phone + '\n')
f.close()
os.fsync()
print "\n"
print " Removed: " + name + " " + phone + " from the phone list.\n"

obviously I have just copied and pasted the def and changed a bit already, are thare any other variables I can change to delete a previous entry?

And pointers in the right direction would be appreciated

Kurtis

Recommended Answers

All 6 Replies

Usually you read in all file do change in memory and write back whole file. Or you have field in line (say first letter) that can be written one value to mark the record deleted (say D or #). The reading routine then ignores those lines.

So do you know how I would be able to read the file incrementally like that? I understand I would be having to program an extra line to mark the recordss, but I am still unsure how to tell it to remove particular records.

I would read the file to a list, find the list item wanted, delete it and write the list to the file.

f = open(addressbook, 'r')
file_records = f.readlines()
f.close()
f = open(addressbook, 'w')
for item in file_records:
    if item != '%s %s \n' % (name, phone):
        f.write(item)

Something like this maybe.

Wow thanks so far tonyjv and Beat_Slayer! I really appreciate your help, but B_S, I still cant quite seem to get your code snippet to run...can I be a bother a bit more and ask you to pretty please take a look at it? Ill upload a .ZIP to this post. If it's too much to worry about don't worry about it though :)

I fixed it for you and made modifications on the list part of the code.

You had also a corrupted file as database, because the format of the lines was not the same you are using now.

What about duplicate entries? I think I'd probably prefer to read the file and parse it into a map, then update the map, and write it back out. Is it time to think about using pickle?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.