下载整个目录(包含文件和子目录)

时间:2014-02-25 13:40:03

标签: python

我想在linux ftp服务器上下载一个包含所有文件和子文件夹/子文件夹的特定目录...

我发现this代码只适用于linux ftp服务器和linux操作系统,但我的操作系统是windows。我查看了代码,它只是对目录结构进行了克隆,因此将"/"替换为"\\"可以完成这项工作。但是我没能使代码工作。

以下是我当前(不工作的代码),我刚刚在相关位置替换了path path.replace("/", "\\")

import sys
import ftplib
import os
from ftplib import FTP
ftp=FTP("ftpserver.com")    
ftp.login('user', 'pass')

def downloadFiles(path,destination):
#path & destination are str of the form "/dir/folder/something/"
#path should be the abs path to the root FOLDER of the file tree to download
  try:
      ftp.cwd(path)
      #clone path to destination
      os.chdir(destination)
      print destination[0:len(destination)-1]+path.replace("/", "\\")
      os.mkdir(destination[0:len(destination)-1]+path.replace("/", "\\"))
      print destination[0:len(destination)-1]+path.replace("/", "\\")+" built"
  except OSError:
      #folder already exists at destination
      pass
  except ftplib.error_perm:
      #invalid entry (ensure input form: "/dir/folder/something/")
      print "error: could not change to "+path
      sys.exit("ending session")

  #list children:
  filelist=ftp.nlst()

  for file in filelist:
      try:
          #this will check if file is folder:
          ftp.cwd(path+file+"/")
          #if so, explore it:
          downloadFiles(path+file+"/",destination)
      except ftplib.error_perm:
          #not a folder with accessible content
          #download & return
          os.chdir(destination[0:len(destination)-1]+path.replace("/", "\\"))
          #possibly need a permission exception catch:
          ftp.retrbinary("RETR "+file, open(os.path.join(destination,file),"wb").write)
          print file + " downloaded"
  return

downloadFiles("/x/test/download/this/",os.path.dirname(os.path.abspath(__file__))+"\\")

输出:

Traceback (most recent call last):
  File "ftpdownload2.py", line 44, in <module>
    downloadFiles("/x/test/download/this/",os.path.dirname(os.path.abspath(__file__))+"\\")
  File "ftpdownload2.py", line 38, in downloadFiles
    os.chdir(destination[0:len(destination)-1]+path.replace("/", "\\"))
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\
Users\\Me\\Desktop\\py_destination_folder\\x\\test\\download\\this\\'

任何人都可以帮我解决这个问题吗?感谢。

1 个答案:

答案 0 :(得分:0)

目录创建似乎与此问题相似,除了由于Windows格式而发生的更改之外,该问题已被提出。

mkdir -p functionality in Python

How to run os.mkdir() with -p option in Python?

因此,我建议在接受这些问题的答案中显示mkdir_p函数,然后查看窗口是否会创建适当的路径

os.mkdir(destination[0:len(destination)-1]+path.replace("/", "\\"))

然后变成

newpath = destination[0:len(destination)-1]+path.replace("/", "\\")
mkdir_p(newpath)

这使用os.makedirs(path)方法来获取完整路径。你也可以用os.makedirs()

替换os.mkdir()

请注意,如果在多个位置使用替换路径,则只需继续使用newpath变量。在其余的代码中,这可能会更容易。