Going through ftp directories in python

2019-08-13 10:54发布

问题:

I'm trying to download several folders from an ftp server with Python 3 using ftplib.

I have a list of the names of the folders. They are all located in a folder 'root'. The problem is that I don't know how to navigate through them. When I use cwdI can go to a deeper directory, but how do I get up again?

I'm trying to get something like

list = ["folder1", "folder2", "folder3"]
for folder in list:
   ##navigate to folder
   ##do something

回答1:

You can retrieve current directory using FTP.pwd method. Remember that directory before change directory.

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


回答2:

I made some changes to code I found here

You have to make the destination folder before running the code. Also, the site I used did not require username or pass.

Please let me know if this works. I am wondering if I should "put this in my back pocket" and save it to my external hard drive.

    #!/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()