我想下載的所有文件和子文件夾/ 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\\'
任何人都可以請幫我把這段代碼工作?謝謝。
作者的這段代碼是否有意義?我認爲問題在於目錄的創建。不是創建'x',然後'test',然後'download' ......它只是創建'/ x/test/download/this /'這是錯誤的,對嗎? – Cecil