Books Database

Alex Martelli aleaxit at yahoo.com
Thu Mar 6 10:37:31 EST 2003


On Thursday 06 March 2003 02:23 pm, Eliran Gonen wrote:
   ...
> > If you're sure you can't have vertical bars within the fields,
> > it could be good.
>
> BTW what do you think is the best way to modify any of those fields
> (in the format of name|author|year) in the future ? put the data in
> a temporary variables modify them, delete the existing line and write
> the line again ?
>
> This is because I want to add a "Loaner" criteria.

Modifying textfiles in-place is not particularly good, but in your case
the file is going to be so small that loading it all, changing the memory
image of the file (a list of lists), and writing it out again overwriting the
existing file, is going to be very fast anyway.  You mentioned 300
books or less, at even 100 characters per line that't still less than 30KB,
a trifling amount of data.

So, read the whole file into a list of lists of strings in memory:

    thefile = open('thefile.txt', 'r+')
    db = [ line[:-1].split('|') for line in thefile ]

change db in-memory at will, then once you're done:

    thefile.seek(0)
    lines = [ '|'.join(fields) for fields in db ]
    thefile.write('\n'.join([ lines ]))
    thefile.close()


Alex






More information about the Python-list mailing list