Compare list entry from csv files

Thomas Bach thbach at students.uni-mainz.de
Thu Nov 29 07:07:34 EST 2012


Can you please cut the message you are responding to the relevant
parts?

On Thu, Nov 29, 2012 at 11:22:28AM +0100, Anatoli Hristov wrote:
> The only problem I have is that I cant compare other field than the
> first one in
> for ex_phone in phones:
>         telstr = ex_phone[0].lower()
> When I use telstr = ex_phone[0].lower() it says out of range and the
> strange think is that the range is 6 I can't figure that out.

As I understood it phones is an csv.reader instance and you are
iterating repeatedly over it. But, csv.reader does not work this
way. You either have to reinstantiate phones with a fresh
file-descriptor (not so good) or cache the values in an appropriate
data structure (better) e.g. a list.

> import csv
> 
> # Open the file with the names and addresses
> origf = open('c:/Working/vpharma.csv', 'rt')
> # Open the  file with the phone numbers
> secfile = open('c:/Working/navori.csv', 'rt')

Note that you never close origf and secfile.

> […]
> # Reads the file with the phone numbers
> # Format "First name","Lastname","Address","City","Country","Phone"
> phones = csv.reader(secfile, delimiter=';')

So this should probably be
PHONES = list(csv.reader(secfile, delimiter=';'))

(in uppercase letters as it is a global)

> […]
> if __name__ == '__main__':
>     name_find()
> 
> # Writes the list to a file
> wfile  = open('c:/Working/ttest.csv', "wb")
> writer = csv.writer(wfile, delimiter=';')
> for insert in namelist:
>     writer.writerow(insert)
> wfile.close()

This should go either in the "if __name__ = …" part or in a function
on its own.

Also have a look at the with statement you can use it in several
places of your code.

There are several other improvements you can make:
+ instead of having the file-names hard coded try to use argparse to
  get them from the command-line,
+ let functions stand at their own and use less globals,
+ try to avoid the use of the type of the data structure in the name
  (e.g. names is IMHO a better name then namelist),
+ add tests.

Regards,
	Thomas



More information about the Python-list mailing list