2014-02-25 214 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變量。在其他代碼中這可能更容易。

相關問題