[Tutor] searching data from a list read from a file
Alan Gauld
alan.gauld at btinternet.com
Sun May 15 21:29:57 CEST 2011
"Lea Parker" <lea-parker at bigpond.com> wrote in
Peter has pointred you to the answer, here are some
general comments:
> def main():
>
> try:
SDee the recent posts re the scope of try/except handling.
This is probably a bit too much for a single exception type!
> # Open file for reading
> infile = open('charge_accounts.txt', 'r')
>
> # Read the contents of the file inot a lsit
> account_number = infile.readlines()
As a point of style if a variabl;e holds a collection of things
use the plural form so this would be batter named
account_numbers
> #Convert each element into an int
> index = 0
> while index != len(account_number):
> account_number[index] = int(account_number[index])
> index += 1
This could be done using map():
account_number = map(int,account_number)
or using a list comprehension:
account_number = [int(num) for num in account_number]
or even using a 'for' loop:
for index, num in enumerate(account_number):
account_number[index] = int(num)
Any of which would be better than the while style.
Use 'while' for cases where you don't know in advance
how many items you need to proccess.
> # Print the contents of the list
> print account_number
> #Get an account number to search for
> search = raw_input('Enter a charge account number: ')
>
> #Determine whether the product number is in thelist
> if search in account_number:
As Peter says, check the types here...
> print search, 'charge account number is VALID'
> else:
> print search, 'charge account number is INVALID'
> infile.close()
> except ValueError:
> print 'file open error message'
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list