aleaxit at yahoo.com
Thu Mar 6 17:55:21 CET 2003
On Thursday 06 March 2003 05:45 pm, John Hunter wrote:
> >>>>> "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
No, don't do that -- if there was an identical entry earlier than the 4th
one you'd be erroneously removing the earlier entry. To remove the
4th item in a list such as books, do instead:
simpler, faster, safer, no reason to do otherwise.
> You can process an individual line with
> vals = books.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.
Yes, I fully concur on this point.
More information about the Python-list