seek in a file
Jim Dennis
jimd at vega.starshine.org
Wed Mar 27 21:56:36 EST 2002
In article <a7s4q4$no0i9$1 at ID-69142.news.dfncis.de>, Andreas Penzel wrote:
>"Steven Majewski" wrote:
>> Are the files too big to fit in memory ?
>the file is about 1 MB, i have to test out working
By today's standards 1Mb is tiny. It should easily fit
in memory on any reasonably recent (last decade or so)
computer.
>> What do you want to do with the lines ?
>> ( I hope you weren't planning on trying to modify a line in a file:
>> because of the variable length on lines, if you don't write
>> exactly the same number of chars back, you will either overwite
>> the next line, or leave an extra partial line after your edited
>> line. Most text editors read the whole file into memory and then
>> write out a new file after it's modified in memory. )
>In the file are barcodes of products, one per line.
>The program has to look if the scanned code from the barcode-scanner is
>identically with one in the file included. This is important because the
>barcode-scanner sometimes works not correct. All i need is an search-routine
>that compares the scanned code with the codes in the file. If there is an
>code, the programs waits for the next code.
So I'd load the file into a dictionary:
f=open('.../barcodes.list','r')
barcodes = {}
for x in f.readlines():
barcodes[x]=None
And then my validation would look like:
while 1:
code=BCodeReader.readline()
while code not in barcodes:
tryAgain()
# use valid code in transactions
# until operator signals to quit
# or forever as you like.
Of course I'm assuming you have some sort of
object "BCodeReader" that acts enough like a
file that you could support a readline() method on
it. In some cases it could actually be a regular
file object, created with the Python open() built-in,
but I don't know about your hardware. I'm also assuming
you'd write a "tryAgain" function.
Of course I recognize that this might be a multi-user
system (possibly with lots of POS terminals attached,
and the bar code scanners attached to those). In that
case consuming a meg or two of memory for the barcodes
dictionary *for each process* might get expensive.
In that case you could create a client/server pair.
The server could simply return "true" or "1" any time
it receives a valid code and "false" or "0" every time
it gets an invalid one. It could be written in about
a dozen lines of Python and it could probably handle
a few hundred concurrent connections (over UNIX or Internet
domain sockets). The client size could be written as
a small class to include in your application probably
also less than a dozen lines of code.
More information about the Python-list
mailing list