简体   繁体   English

使用Python列出FTP中所有子目录中的所有文件

[英]List all the files in all subdirectories from an FTP using Python

I'm new to Python and I'm trying to list all the files in all the sub-directories from an FTP. 我是Python的新手,我正在尝试列出FTP中所有子目录中的所有文件。 The FTP, as usual, is in this format. 像往常一样,FTP采用这种格式。

 A
 B
 C

Subdirectories : 子目录:

 AA
 BB
 CC

I could list the directories ['A', 'B', 'C'] using ftp.nlist() . 我可以使用ftp.nlist()列出目录['A', 'B', 'C'] I'd like to get ['AA', 'BB', 'CC'] as my output. 我想把['AA', 'BB', 'CC']作为我的输出。 I've tried and looked up a lot to find a solution/hint to do this. 我已经尝试并查找了很多来找到解决方案/提示来做到这一点。

I know this is a bit old, but an answer here could have saved me a bit of effort, so here it is. 我知道这有点老了,但这里的答案本可以省去一些努力,所以现在就是这样。 I'm a bit of an amateur, so this is probably not the most efficient way, but here is a program I wrote to get all directories on an FTP server. 我有点像业余爱好者,所以这可能不是最有效的方式,但这是我写的一个程序来获取FTP服务器上的所有目录。 It will list all directories no matter how far they are down 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM