要在Python中列出的文本文件

时间:2011-01-12 18:36:30

标签: python

假设我有一个名为test1.txt的文档,其中包含以下数字:

133213
123123
349135
345345

我希望能够获取每个号码并将其附加到以下URL的末尾以发出HTTP请求。如何将id填入列表并调用每个?这是我到目前为止所做的。

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

4 个答案:

答案 0 :(得分: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
... 

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分: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与您的计划相同。

答案 3 :(得分:0)

使用file.readlines()读取所有值,删除每行结尾'\ n'的行,其余为您的编号。