python ftp 按目录结构上传下载的实现代码
具体代码如下所示:
#!/usr/bin/python #coding=utf-8 fromftplibimportFTP importtime importos def__ftp_upload(ftp,local,remote,isDel=False): ifos.path.isdir(local): forfinos.listdir(local): ifos.path.isdir(local+f): try: ftp.cwd(remote+f) except: ftp.mkd(remote+f) printlocal+f __ftp_upload(ftp,local+f+'/',remote+f+'/',isDel) else: printremote+f printlocal+f fp=open(local+f,'rb') ftp.storbinary('STOR'+remote+f,fp,4096) fp.close() if(isDel==True): os.remove(local) else: fp=open(local+f,'rb') ftp.storbinary('STOR'+remote+f,fp,4096) fp.close() if(isDel==True): os.remove(local) defftp_upload(host,port,username,password,local,remote,isDel=False): ftp=FTP() try: ftp.connect(host,port) ftp.login(username,password) except: returnFalse try: __ftp_upload(ftp,local,remote,False) exceptException,e: printe ftp.close() returnTrue defftp_download(host,port,username,password,local,remote): ftp=FTP() ftp.connect(host,port) ftp.login(username,password) ret=False try: ifos.path.isdir(local): forfinftp.dir(remote): fp=open(local+f,'wb') ftp.retrbinary('RETR'+remote+f,fp.write,4096) fp.close() else: fp=open(local,'wb') ftp.retrbinary('RETR'+remote,fp.write,4096) fp.close() ret=True exceptException,e: print("downloadexception:\n",e) ftp.close() returnret if__name__=='__main__': host='*.*.*.*' port='21' username='xxx' password='xxx' ftp_upload(host,port,username,password,'/home/pi/work/xx/','/home/ubuntu/xx/',False) print'download' ftp_download(host,port,username,password,'/home/pi/work/xx/hh.txt','/home/ubuntu/xx/hh.txt')
只完成了按目录结构上传,下载还没弄好。
补充:下面看下Pythonftp上传和下载
工具
python3
ftplib
上传
fromftplibimportFTP ftp=FTP(host='127.0.0.1',user='test',passwd='test')#创建 ftp.cwd('/home/test/ftp/')#上传路径 fd=open('test.txt','rb')#以只读的方式打开要上传的文件 ftp.storbinary('STORtest.txt',fd)#上传文件 fd.close() ftp.quit()#退出登录 ftp.close()#关闭连接
下载
fromftplibimportFTP ftp=FTP(host='127.0.0.1',user='test',passwd='test')#创建 ftp.cwd('/home/test/ftp/')#服务器下载路径 fd=open('test.txt','wb')#以只写的方式打开要下载的文件 ftp.retrbinary('RETRtest.txt',fd.write,2048)#下载文件 fd.close() ftp.quit()#退出登录 ftp.close()#关闭连接
总结
以上所述是小编给大家介绍的jpythonftp按目录结构上传下载的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!