Books Database

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Mar 6 17:45:08 CET 2003


>>>>> "Eliran" == Eliran Gonen <eg at rootshell.be> writes:

    Eliran> 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.

    Eliran> Nope. I meant, let say I have a file:

    Eliran> 1|2|3|4 2|3|4|5 a|b|c|d d|b|a|c

    Eliran> and the user want to remove line 3 (a|b|c|d).  So in my
    Eliran> curses application he enters '3' and then I need to remove
    Eliran> line 3. I can not know how many characters are there so I
    Eliran> have to count \n's


If you want to keep track of lines by number you can do

  books = file('books.dat').readlines()

If you want to remove the 4th entry (indexing from 0), do

  books.remove(books[3])

You can process an individual line with

  vals = books[2].split('|')

When you are done and want to save the results, you can do

  file('books.dat', 'w').writelines(books)

But the point is that you process everything in memory and then
overwrite the file when done rather that trying to manipulate
the individual lines of the file directly.

John Hunter





More information about the Python-list mailing list