我正在尝试使用ftplib从Python 3下载ftp服务器中的几个文件夹。
我有一个文件夹名称列表。它们都位于文件夹“root”中。问题是我不知道如何浏览它们。当我使用cwd
时,我可以访问更深层的目录,但如何再次启动?
我正试图获得像
这样的东西list = ["folder1", "folder2", "folder3"]
for folder in list:
##navigate to folder
##do something
答案 0 :(得分:1)
您可以使用FTP.pwd
方法检索当前目录。在更改目录之前请记住该目录。
parent_dir = ftp_object.pwd()
list = ["folder1", "folder2", "folder3"]
for folder in list:
ftp_object.cwd('{}/{}'.format(parent_dir, folder))
ftp_object.cwd(parent_dir) # go to parent directory
答案 1 :(得分:0)
我对找到的here代码进行了一些更改
在运行代码之前,必须创建目标文件夹。 另外,我使用的网站不需要用户名或密码。
请告诉我这是否可行。我想知道是否应该“把它放在我的后兜里”并将其保存到我的外部硬盘驱动器中。
#!/usr/bin/python
import sys
import ftplib
import urllib.request
import os
import time
import errno
server = "ftp.analog.com"
#user = ""
#password = ""
source = "/pub/MicroConverter/ADuCM36x/"
destination0 = "C:/NewFolder/" # YOU HAVE TO UT THIS NEW FOLDER IN C: BEFORE RUNNING
interval = 0.05
ftp = ftplib.FTP(server)
ftp.login()#(user, password)
count = 0 #We need this variable to make the first folder correctly
def downloadFiles(path, destination):
try:
ftp.cwd(path)
os.chdir(destination)
mkdir_p(destination[0:len(destination)-1] + path)
print ("Created: " + destination[0:len(destination)-1] + path )
except OSError:
pass
except ftplib.error_perm:
print ( "Error: could not change to " + path )
sys.exit("Ending Application")
filelist=ftp.nlst()
print(filelist)
for file in filelist:
time.sleep(interval)
if "." in file :
url = ("ftp://" + server + path + file)
urllib.request.urlretrieve(url, destination + path + file)
else:
try:
ftp.cwd(path + file + "/")
downloadFiles(path + file + "/", destination)
except ftplib.error_perm:
os.chdir(destination[0:len(destination)-1] + path)
try:
ftp.retrbinary("RETR " + file, open(os.path.join(destination + path, file),"wb").write)
print ("Downloaded: " + file)
except:
print ("Error: File could not be downloaded " + file)
return
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
downloadFiles(source, destination0)
#ftp.quit()