python从ftp获取文件并下载到本地
最近有需求是,需要把对方提供的ftp地址上的图片获取到本地服务器,原先计划想着是用shell 操作,因为shell 本身也支持ftp的命令 在通过for 循环也能达到需求。但是后来想着 还是拿python 操作;于是在网上进行百度;无一例外 还是那么失望 无法直接抄来就用。于是在一个代码上进行修改。还是有点心东西学习到了;具体操作代码如下 只要修改ftp 账号密码 已经对应目录即可使用
在这需要注意一点的是os.path.join 的用法需要注意
#!/usr/bin/python# -*- coding: utf-8 -*-'''FTP常用操作'''from ftplib import FTPimport osclass FTP_OP(object): def __init__(self, host, username, password, port): ''' 初始化ftp :param host: ftp主机ip :param username: ftp用户名 :param password: ftp密码 :param port: ftp端口 (默认21) ''' self.host = host self.username = username self.password = password self.port = port def ftp_connect(self): ''' 连接ftp :return: ''' ftp = FTP() ftp.set_debuglevel(1) # 不开启调试模式 ftp.connect(host=self.host, port=self.port) # 连接ftp ftp.login(self.username, self.password) # 登录ftp ftp.set_pasv(False)##ftp有主动 被动模式 需要调整 return ftp def download_file(self, ftp_file_path, dst_file_path): ''' 从ftp下载文件到本地 :param ftp_file_path: ftp下载文件路径 :param dst_file_path: 本地存放路径 :return: ''' buffer_size = 102400 #默认是8192 ftp = self.ftp_connect() print(ftp.getwelcome() ) #显示登录ftp信息 file_list = ftp.nlst(ftp_file_path) for file_name in file_list: print('file_name'+file_name) ftp_file = os.path.join(ftp_file_path, file_name) print('ftp_file:'+ftp_file) #write_file = os.path.join(dst_file_path, file_name) write_file = dst_file_path+file_name ##在这里如果使用os.path.join 进行拼接的话 会丢失dst_file_path路径,与上面的拼接路径不一样 print('write_file'+write_file) if file_name.find(’.png’)>-1 and not os.path.exists(write_file):print('file_name:'+file_name)#ftp_file = os.path.join(ftp_file_path, file_name)#write_file = os.path.join(dst_file_path, file_name)with open(write_file, 'wb') as f: ftp.retrbinary(’RETR %s’ % ftp_file, f.write, buffer_size) #f.close() ftp.quit()if __name__ == ’__main__’: host = '192.168.110.**' username = '****' password = '****' port = 21 ftp_file_path = '/erp-mall/' #FTP目录 dst_file_path = '/root/11' #本地目录 ftp = FTP_OP(host=host, username=username, password=password, port=port) ftp.download_file(ftp_file_path=ftp_file_path, dst_file_path=dst_file_path)
以上就是python从ftp获取文件并下载到本地的详细内容,更多关于python ftp下载文件的资料请关注好吧啦网其它相关文章!
相关文章:
1. 《CSS3实战》笔记--渐变设计(一)2. 通过CSS实现逼真水滴动效3. 一个用xslt样式将xml解析为xhtml的类TransformBinder(兼容FF和IE7.0)4. HTML5实战与剖析之触摸事件(touchstart、touchmove和touchend)5. XML入门的常见问题(三)6. asp与php中定时生成页面的思路与代码7. asp下利用xml打包网站文件8. XML CDATA是什么?9. HTTP与HTTPS超文本传输协议的区别是什么10. vue-element-admin中node-sass换成dart-sass,安装依赖报code 128多种问题的解决方法
