Books Database

Alex Martelli aleaxit at yahoo.com
Thu Mar 6 17:41:26 CET 2003


On Thursday 06 March 2003 05:07 pm, Eliran Gonen wrote:
> Alex Martelli <aleaxit at yahoo.com>:
> > NAH!  Why do so much work?!  Just read the db into
> > memory, remove whatever you want from the db
> > _variable_, and overwrite as above.  At 30KB file size,
> > or even quite a bit more, that will be lightning-fast.
>
> Nope. I meant, let say I have a file:
>
> 1|2|3|4
> 2|3|4|5
> a|b|c|d
> d|b|a|c
>
> and the user want to remove line 3 (a|b|c|d).
> So in my curses application he enters '3' and then
> I need to remove line 3. I can not know how many characters
> are there so I have to count \n's

You dont't *HAVE* to count anything!  If for whatever
weird reason you don't currently have the db in memory
(I can't understand why you wouldn't load it at application
startup and keep it in memory throughout), you can "delete
line X of file Y" in the simplest way by:
    thefile = open('X','r+')
    lines = thefile.readlines()
    del lines[X]
    thefile.seek(0)
    thefile.writelines(lines)
    thefile.close()
given that the file isn't too huge.

If you DID go to the trouble of counting '\n's, what would
you do then?  And why?


Alex






More information about the Python-list mailing list