List all files in all subdirectories with FTP using Python

I am new to Python and I am trying to list all files in all subdirectories with FTP. FTP, as usual, is in this format.

 A
 B
 C

      

Subdirectories:

 AA
 BB
 CC

      

I could list directories ['A', 'B', 'C']

with ftp.nlist()

. I would like to receive ['AA', 'BB', 'CC']

as my conclusion. I've tried and searched a lot to find a solution / hint for this.

+3


source to share


1 answer


I know this is a little out of date, but the answer here might save me a little effort, so here it is. I'm a bit of a hobbyist, so this is probably not the most efficient way, but here is a program I wrote to get all directories on an FTP server. It will list all directories no matter how far from the tree.



from ftplib import FTP

def get_dirs_ftp(folder=""):
    contents = ftp.nlst(folder)
    folders = []
    for item in contents:
        if "." not in item:
            folders.append(item)
    return folders

def get_all_dirs_ftp(folder=""):
    dirs = []
    new_dirs = []

    new_dirs = get_dirs_ftp(folder)

    while len(new_dirs) > 0:
        for dir in new_dirs:
            dirs.append(dir)

        old_dirs = new_dirs[:]
        new_dirs = []
        for dir in old_dirs:
            for new_dir in get_dirs_ftp(dir):
                new_dirs.append(new_dir)

    dirs.sort()
    return dirs


host ="your host"
user = "user"
password = "password"

print("Connecting to {}".format(host))
ftp = FTP(host)
ftp.login(user, password)
print("Connected to {}".format(host))

print("Getting directory listing from {}".format(host))
all_dirs = get_all_dirs_ftp()
print("***PRINTING ALL DIRECTORIES***")
for dir in all_dirs:
    print(dir)

      

+2


source







All Articles