码迷,mamicode.com
首页 > 编程语言 > 详细

python ftplib下载文件封装

时间:2018-04-20 14:38:56      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:orm   net   %s   col   用户密码   val   import   nes   nbsp   

原用于下载ftp中文路径图片封装代码

  1. 支持指定用户密码和端口
    ftp://ftpuser:ftppasswd@192.168.2.157:21/test.png
  2. 支持中文
    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下载文件封装

标签:orm   net   %s   col   用户密码   val   import   nes   nbsp   

原文地址:https://www.cnblogs.com/elephanyu/p/8889428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!