具體代碼如下所示:
#!/usr/bin/python# coding=utf-8from ftplib import FTPimport timeimport osdef __ftp_upload(ftp,local,remote,isDel=False): if os.path.isdir(local): for f in os.listdir(local): if os.path.isdir(local+f): try: ftp.cwd(remote+f) except: ftp.mkd(remote+f) print local+f __ftp_upload(ftp,local+f+'/',remote+f+'/',isDel) else: print remote+f print local+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)def ftp_upload(host,port,username,password,local,remote,isDel=False): ftp = FTP() try: ftp.connect(host,port) ftp.login(username,password) except: return False try: __ftp_upload(ftp,local,remote,False) except Exception,e: print e ftp.close() return Truedef ftp_download(host,port,username,password,local,remote): ftp = FTP() ftp.connect(host,port) ftp.login(username,password) ret = False try: if os.path.isdir(local): for f in ftp.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 except Exception,e: print ("download exception:/n",e) ftp.close() return retif __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')
只完成了按目錄結構上傳,下載還沒弄好。
補充:下面看下Python ftp 上傳和下載
工具
python3
ftplib
上傳
from ftplib import FTPftp = FTP(host='127.0.0.1', user='test', passwd='test') #創建ftp.cwd('/home/test/ftp/') #上傳路徑fd = open('test.txt', 'rb') #以只讀的方式打開要上傳的文件ftp.storbinary('STOR test.txt', fd) #上傳文件fd.close()ftp.quit() #退出登錄ftp.close() #關閉連接
下載
from ftplib import FTPftp = FTP(host='127.0.0.1', user='test', passwd='test') #創建ftp.cwd('/home/test/ftp/') #服務器下載路徑fd = open('test.txt', 'wb') #以只寫的方式打開要下載的文件ftp.retrbinary('RETR test.txt', fd.write, 2048) #下載文件fd.close()ftp.quit() #退出登錄ftp.close() #關閉連接
總結
以上所述是小編給大家介紹的jpython ftp 按目錄結構上傳下載的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林站長站網站的支持!
新聞熱點
疑難解答