2014-02-25 144 views
0

我想下载的所有文件和子文件夹/ subsubfolders一个Linux FTP服务器上的特定目录...下载整个目录(包含文件和子目录)

我发现this代码只工作了一个linux FTP服务器和Linux操作系统,但我的操作系统是Windows。我检查了代码,它只是制作目录结构的克隆,因此用"\\"代替"/"应该可以完成这项工作。但是我没有使代码工作。

这是我目前在这里我只是path.replace("/", "\\")对有关地方更换path(不工作密码):

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\\' 

任何人都可以请帮我把这段代码工作?谢谢。

+0

作者的这段代码是否有意义?我认为问题在于目录的创建。不是创建'x',然后'test',然后'download' ......它只是创建'/ x/test/download/this /'这是错误的,对吗? – Cecil

回答

0

目录创建似乎与此问题类似,除了由于Windows格式导致的更改外,这个问题已经被问到。

mkdir -p functionality in Python

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

因此,我建议把在接受这些问题的答案显示的mkdir_p函数,然后看如果Windows将创建适当的路径

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

然后变成

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

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

请注意,如果你在很多地方使用了替换路径,那么就继续使用newpath变量。在其他代码中这可能更容易。

相关问题