python从ftp获取文件并下载到本地
最近有需求是,需要把对方提供的ftp地址上的图片获取到本地服务器,原先计划想着是用shell操作,因为shell本身也支持ftp的命令在通过for循环也能达到需求。但是后来想着还是拿python操作;于是在网上进行百度;无一例外还是那么失望无法直接抄来就用。于是在一个代码上进行修改。还是有点心东西学习到了;具体操作代码如下只要修改ftp账号密码已经对应目录即可使用
在这需要注意一点的是os.path.join的用法需要注意
#!/usr/bin/python #-*-coding:utf-8-*- """ FTP常用操作 """ fromftplibimportFTP importos classFTP_OP(object): def__init__(self,host,username,password,port): """ 初始化ftp :paramhost:ftp主机ip :paramusername:ftp用户名 :parampassword:ftp密码 :paramport:ftp端口(默认21) """ self.host=host self.username=username self.password=password self.port=port defftp_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有主动被动模式需要调整 returnftp defdownload_file(self,ftp_file_path,dst_file_path): """ 从ftp下载文件到本地 :paramftp_file_path:ftp下载文件路径 :paramdst_file_path:本地存放路径 :return: """ buffer_size=102400#默认是8192 ftp=self.ftp_connect() print(ftp.getwelcome())#显示登录ftp信息 file_list=ftp.nlst(ftp_file_path) forfile_nameinfile_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) iffile_name.find('.png')>-1andnotos.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) withopen(write_file,"wb")asf: 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获取文件并下载到本地的详细内容,更多关于pythonftp下载文件的资料请关注毛票票其它相关文章!