开发者

Text file to list in Python

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开发者_StackOverflow中文版 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()


>>> 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
... 


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()


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜