python ftplib下载文件封装
Posted 宇之逸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python ftplib下载文件封装相关的知识,希望对你有一定的参考价值。
原用于下载ftp中文路径图片封装代码
- 支持指定用户密码和端口
ftp://ftpuser:[email protected]:21/test.png
- 支持中文
ftp://192.168.2.157/测试1/test.png
直接上代码
1 # coding:utf-8 2 import sys 3 import urlparse 4 import ftplib 5 import traceback 6 import StringIO 7 8 # used to down ftp file with auth and chinese character 9 def ftpdown(url, timeout=3): 10 lasterr = ‘‘ 11 for i in range(3): 12 urlps = urlparse.urlparse(url) 13 if ‘@‘ not in urlps.netloc: 14 user = ‘‘ 15 passwd = ‘‘ 16 host = urlps.netloc 17 port = 21 18 else: 19 urlhead = urlps.netloc.split(‘@‘) 20 if len(urlhead) != 2: 21 lasterr = ‘url fromat err‘ 22 continue 23 else: 24 user, passwd = urlhead[0].split(‘:‘) 25 if ‘:‘ not in urlhead[1]: 26 host = urlhead[1] 27 port = 21 28 else: 29 host, port = urlhead[1].split(‘:‘) 30 31 try: 32 ftp = ftplib.FTP() 33 ftp.connect(host=host, port=port, timeout=timeout) 34 ftp.login(user=user, passwd=passwd) 35 except Exception: 36 print(traceback.format_exc()) 37 continue 38 try: 39 buf = StringIO.StringIO() 40 ftp.retrbinary(‘RETR ‘ + urlps.path, buf.write) 41 ftp.close() 42 return buf.getvalue() 43 except Exception: 44 lasterr = traceback.format_exc() 45 continue 46 print(‘exception occurs when ftp get url[%s], err[%s]‘ % (url, lasterr)) 47 return None
以上是关于python ftplib下载文件封装的主要内容,如果未能解决你的问题,请参考以下文章