欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python ftp 按目录结构上传下载的实现代码

程序员文章站 2022-05-04 13:29:38
具体代码如下所示: #!/usr/bin/python # coding=utf-8 from ftplib import ftp import time...

具体代码如下所示:

#!/usr/bin/python
# coding=utf-8
from ftplib import ftp
import time
import os
def __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 true
def 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 ret
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')

只完成了按目录结构上传,下载还没弄好。

补充:下面看下python ftp 上传和下载

工具

python3
ftplib

上传

from ftplib import ftp
ftp = 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 ftp
ftp = 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 按目录结构上传下载的实现代码,希望对大家有所帮助