Compare list entry from csv files

Neil Cerutti neilc at
Tue Nov 27 21:41:57 CET 2012

On 2012-11-27, Anatoli Hristov <tolidtm at> wrote:
> Thank you all for the help, but I figured that out and the
> program now works perfect. I would appreciate if you have some
> notes about my script as I'm noob :) Here is the code:
> import csv
> origf = open('c:/Working/Test_phonebook.csv', 'rt')
> secfile = open('c:/Working/phones.csv', 'rt')

csv module expects files to be opened in binary mode in Python
versions less than version 3.0. For Python versions >= 3.0, you
use the special keyword argument, newlines='', instead.

> phonelist = []
> namelist = []

The structure of your program is poor. It's workable for such a
short script, and sometimes my first cuts are similar, but it's
better to get out of the habit right away.

Once you get this working the way you'd like you should clean up
the structure as a service to your future self.

> names = csv.reader(origf, delimiter=';')
> phones = csv.reader(secfile, delimiter=';')

You csv files don't seem to have header rows, but even so you can
improve your code by providing fieldnames and using a DictReader

name_reader = csv.DictReader(origf, fieldnames=[
                                     'Name', 'Blah', 'Phone#'])

Then you can read from records with

  name = row['Name']

instead of using bare, undocumented integers.

> for tel in phones:
>     phonelist.append(tel)
> def finder(name_row,rows):
>     for ex_phone in phonelist:
>         telstr = ex_phone[0].lower()
>         if telstr.find(name_row) >= 0:

This strikes me as a crude way to match names. You don't really
want Donald to match perfectly with McDonald, do you? Or for
Smith to match with Smithfield?

Yes, a human being will clean it up, but your program can do a
better job.

>             print "\nName found: %s" % name_row
>             namelist[rows][-1] = ex_phone[-1].lower()
>         else:
>             pass
>     return
> def name_find():
>     rows = 0
>     for row in names:
>         namelist.append(row)
>         name_row = row[0].lower()
>         finder(name_row,rows)
>         rows = rows+1

You can use the useful enumerate function instead of your own

      for rows, row in enumerate(names):

...though I would find 'rownum' or 'num' or just 'i' better than
the name 'rows', which I find confusing.

> name_find()
> ofile  = open('c:/Working/ttest.csv', "wb")
> writer = csv.writer(wfile, delimiter=';')
> for insert in namelist:
>     writer.writerow(insert)
> wfile.close()

Neil Cerutti

More information about the Python-list mailing list