簡體   English   中英

要在Python中列出的文本文件

[英]Text file to list in 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()
>>> 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
... 

嘗試這個:

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與您的程序相同。

使用file.readlines()讀取所有值,刪除每行以'\\ n'結尾的行,其余就是您的電話號碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM