0

Suppose I have a document called test1.txt that contains the following numbers:

133213
123123
349135
345345

I want to be able to take each number and append it to the end of the URL below to make a HTTP request. How do I stuff the id's into a list and call each one? This is what I have so far.

file = open('C:\Users\Owner\Desktop\\test1.txt')
startcount = 1
endcount = len(file.readlines())

o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )

while startcount < endcount:

    f = o.open( 'http://www.test.com/?userid=' + ID GOES HERE )
    f.close()
1
  • .readlines() consumes the entire file. Commented Jan 12, 2011 at 18:39

4 Answers 4

2
>>> from urllib import urlencode
>>> with open('C:\Users\Owner\Desktop\\test1.txt') as myfile:
...     for line in myfile:
...             params = urlencode({'userid': line.strip()})
...             f = opener.open('http://www.test.com/?' + params)
...             # do sth
... 
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

o = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(o)

file = open('C:\Users\Owner\Desktop\\test1.txt')
for line in file:    
    f = o.open('http://www.test.com/?userid=' + line.rstrip())
    f.close()

Comments

0
id_file = [line.strip() for line in open('/file/path')]  # path to file    
# so id_file is a list: ['133213', '123123', '349135', '345345']

url = 'http://www.test.com/?userid='                     # url    
for ele in id_file:                                               
        f = o.open(url + ele)

o being the same as in your program.

Comments

0

read all the value using file.readlines(), remove the line ending '\n' for each line, and the rest is your number.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.