python 批量下载文件

file.txt 的内容为:

http://183.xxx.xxx.54:188/my/qqq.ico::qq.exe::0::
http://183.xxx.xxx.54:186/my/ddnf.ico::dnf.exe::0::

 1 import re
 2 import os.path
 3 import urllib.request
 4 import socket
 5 
 6 #Python读写文件
 7 #使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
 8 
 9 n=0
10 file_object = open('file.txt')  #读文本文件,第二个参数默认为r
11 #all_the_text = file_object.read( )
12 for line in file_object: #如果文件是文本文件,还可以直接遍历文件对象获取每行:
13     try:
14         n = n+1
15         #print (line,end="") #python 3.x  print 不换行
16         pattern = re.compile(r'(.+?)::.+')
17         match = pattern.search(line)
18         if match:
19             url = match.group(1)
20             p,filename = os.path.split(url)
21             socket.setdefaulttimeout(10) #设置超时
22             data = urllib.request.urlretrieve(url,filename)
23             print(url)
24     except Exception as e:
25         print(e,url)
26         n = n-1
27 print(n)
28 file_object.close( ) #注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
原文地址:https://www.cnblogs.com/homeways/p/5041218.html