searching files

Chris Liechti cliechti at gmx.net
Sat May 11 14:24:37 EDT 2002


"zweistein" <zweistein at net.hr> wrote in news:abjm4j$lmd$1 at bagan.srce.hr:

> "Chris Liechti" <cliechti at gmx.net> wrote in message
> news:Xns920BB71141B16cliechtigmxnet at 62.2.16.82...
>> please provide more information about your data structure and what
>> exactly you want to search (names, numbers etc) and you will get more
>> useful feedback from this group.
> 
> Well, I am storing every entry in a file. It stores only the name and
> the telephone number, and is tab delimited (name surname [TAB] tel.).

in the spirit of ReiserFS (he says you would need a database if your 
filesystem would be good enough)... a file per entry... oh well, surely a 
possibility but not the simplest. (storing all addresses in the same file, 
one line per address, tab delimited entries per line would be simpler)

you could also laod and save pickled python data i.e. save the whole 
address list in a file and open it on the next run. that way you don't have 
to encode/decode textfiles yourself.

> I am trying to write a function to which a searchstring would be
> passed which would look into the entire file and show the entry that
> matches. I would like it to search both names and tel. numbers.

load all addresses in a list then search though the list.

with one line per file:

for filename in os.listdir('databasedir')
    	addressList = []
    	addressList.append(open(filename).read().split('\t'))

this gives you a list of lists like:
addressList = [
    	['chris', '1234'],
    	['zweistein', '1234'],
]

so you can search:
for name,number in addressList:
    	if name == 'chris':
    	    	print name, number
    	    	break #found one, don't search for more
else:
    	print "no matching entries found"

as you see there is no errorchecking in the above bits, for a real usabel 
programm one should check for illegal entries etc.

a more advanced approch using classes could also be interesting...

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list