我想下载的所有文件和子文件夹/ 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