3
\$\begingroup\$

I'm tasked with getting emails from a .csv file and using them to submit a form. I am using the csv and mechanize Python libraries to achieve this.

import re
import mechanize
import csv
def auto_email(email):
 br = mechanize.Browser()
 br.open("URL")
 br.select_form(name="vote_session")
 br['email_add'] = '%s' % (email) #email address
 br.submit()
def csv_emails():
 ifile = open('emails.csv', "rb") 
 reader = csv.reader(ifile)
 rownum = 1
 for row in reader:
 auto_email(row[0])
 print "%d - %s processed" %(rownum, row[0])
 rownum += 1
 print 'List processed. You are done.'
 ifile.close()
print csv_emails()

The code works, but I am very much a beginner in Python.

I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jan 15, 2013 at 16:16
\$\endgroup\$

2 Answers 2

6
\$\begingroup\$

I would suggest to use

with open('emails.csv', "rb") as ifile

see here for details: http://www.python.org/dev/peps/pep-0343/ in this case you don't need to do ifile.close at the end

instead of incrementing rownum by yourself, you can use

for row, rownum in enumerate(reader):

I don't see the reason to do this

br['email_add'] = '%s' % (email) #email address

instead of

br['email_add'] = email
answered Jan 15, 2013 at 17:01
\$\endgroup\$
2
  • \$\begingroup\$ email comes from a row returned by csv.reader so it's always a string. \$\endgroup\$ Commented Jan 15, 2013 at 17:03
  • \$\begingroup\$ so in this case br['email_add'] = email is enough. I edited my answer \$\endgroup\$ Commented Jan 15, 2013 at 17:04
1
\$\begingroup\$

print csv_emails() doesn't make sense. Since csv_emails() returns no value, there is nothing to print.

answered Jun 6, 2014 at 2:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.