Compare list entry from csv files

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Nov 29 18:13:25 EST 2012


Anatoli Hristov wrote:
> Hello,
> 
> Tried to document a little bit the script, but I'm not that good in that too :)
> 
> 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. So when
> I edit the csv I modify the look of the file and then I start the
> script and it works, but I wanted to use more than one condition and I
> can't :(
> 
> 

Can you print ex_phone first. You are opening the files in text mode
so I wonder if the line endings are causing you to read and extra
"line" in between. Can you try reading the csv as "rb" instead of 
"rt"?

> 
> 
> 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')
> 
> # Creates the empty list with the names
> namelist = []
> # Creates the empty list with the phone numbers
> PHONELIST = []
> 
> 
> # Reads the file with the names
> # Format "Name","Phone"
> names = csv.reader(origf, delimiter=';')
> 
> # Reads the file with the phone numbers
> # Format "First name","Lastname","Address","City","Country","Phone"
> phones = csv.reader(secfile, delimiter=';')
> 
> # Creates a list with phone numbers
> #for tel in phones:
> #    PHONELIST.append(tel)
> 
> 
> def finder(Compare_Name,rows):
>     '''
>     Compare the names from the namelist with the names from the phonelist.
>     If the name match - then the phone number is added to the specified field
>     '''
>     for ex_phone in phones:
>         telstr = ex_phone[0].lower()
>         print telstr
>         if telstr.find(Compare_Name) >= 0:
>             print "\nName found: %s" % Compare_Name
>             namelist[rows][-1] = ex_phone[-1].lower()
>         else:
>             print "Not found %s" % Compare_Name
>             pass
>     return
> 
> def name_find():
>     rows = 0
>     for row in names:
>         namelist.append(row)
>         Compare_Name = row[1].lower()
>         finder(Compare_Name,rows)
>         rows = rows+1
> 
> 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()


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list