【发布时间】:2014-02-25 13:40:02
【问题描述】:
我想在 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\\'
谁能帮我把这段代码弄好?谢谢。
【问题讨论】:
-
作者的这段代码真的有意义吗?我认为问题是目录创建。而不是创建
x,然后是test,然后是download...它只是创建/x/test/download/this/,这是错误的,对吧?
标签: python