[Tutor] Looking for some utilities
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri Jul 25 19:46:02 2003
On Fri, 25 Jul 2003, Emily Lea Connally wrote:
> Hey everyone, I'm very new to programming, in fact, Python is my first
> language.
Hi Emily, welcome aboard!
> I need to read the file and search for an address that the user had
> entered earlier in the program and delete that address if found.
Sounds good so far.
> Can I do this using a text file or should I set up a database or what?
> Sorry if this question is a little elementary, but I am honestly brand
> new to programming and really stuck here.
No problem. Your program sounds like a kind of "filtering" task, where we
try to only keep things that fit a certain criteria. Here's an concrete
example of filtering a list of numbers for "even" numbers:
###
>>> numbers = range(20)
>>> def is_even(x):
... return x % 2 == 0
...
>>> filtered_numbers = []
>>> for num in numbers:
... if is_even(num):
... filtered_numbers.append(num)
...
>>> filtered_numbers
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
###
Here, our "criteria" is checking to see if a number "is_even()". The idea
of filtering is general enough that it'll apply to any list of elements
--- not just numbers.
If you load your address file into a list, you can apply a similar
filtering, and then write the filtered result back to disk. Doing
manipulations (like deleting or inserting elements) is easy to do on
lists, so if your entire address book can fit in memory, the
list-manipulation approach should work well.
It's not the most "efficient" way to do things, but it's simple. *grin*
There are other approaches to your problem, and we can talk about them if
you'd like.
Please feel free to ask questions on Tutor; we'll be happy to help!