Python实现连接FTP并下载文件夹

  import pathlib

  def download_dir(ftp, path, local_path):

  '''

  作用: 下载目录

  参数1:ftp连接对象

  参数2:要展示的目录

  参数3:本地存放路径

  返回:无

  '''

  # 进入指定目录

  ftp.cwd(path)

  # 区分文件和文件夹

  dirs = []

  ftp.dir(".", dirs.append)

  for i in dirs:

  try:

  # 识别为目录进行递归

  if("

" in i):

  dir_name = get_dir_name(i)

  local_path_new = local_path + "/" + dir_name

  # 本地创建文件夹

  pathlib.Path(local_path_new).mkdir(parents=True, exist_ok=True)

  # 调用下载目录方法

  download_dir(ftp, dir_name, local_path_new)

  # 识别为文件进行下载

  else:

  file_name = get_dir_name(i)

  local_filename = local_path + "/" + file_name

  f = open(local_filename, "wb")

  # 下载ftp文件

  ftp.retrbinary('RETR ' + file_name, f.write)

  f.close()

  except Exception as e:

  print(e)

  # 退出当前目录

  ftp.cwd("..")

  def download_file(ftp, key, path, local_path):

  '''

  作用: 根据关键词下载文件

  参数1:ftp连接对象

  参数2:下载的关键词

  参数3:要展示的目录

  参数4:本地存放路径

  返回:无

  '''

  # 进入指定目录

  ftp.cwd(path)

  # 区分文件和文件夹

  dirs = []

  ftp.dir(".", dirs.append)

  for i in dirs:

  if(key in i):

  try:

  # 识别为目录进行递归

  if("

" in i):

  dir_name = get_dir_name(i)

  local_path_new = local_path + "/" + dir_name

  # 本地创建文件夹

  pathlib.Path(local_path_new).mkdir(parents=True, exist_ok=True)

  # 调用下载目录方法

  download_dir(ftp, dir_name, local_path_new)

  else:

  file_name = get_dir_name(i)

  local_filename = local_path + "/" + file_name

  f = open(local_filename, "wb")

  # 下载ftp文件

  ftp.retrbinary('RETR ' + file_name, f.write)

  f.close()

  except Exception as e:

  print(e)

  # 设置编码,解决上传的文件包含中文的问题

  ftp.encoding = 'GBK'

  key = "C2021.11_ZDHJC"

  path = "/CaseData/nc.vo.sdp.testcase.testcase.TestcaseHVO/"

  local_path = "D:/ftp下载"

  download_file(ftp, key, path, local_path)