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

标签 python ftp subdirectory ftplib filelist

我是 Python 的新手,我正在尝试从 FTP 列出所有子目录中的所有文件。 像往常一样,FTP 就是这种格式。

 A
 B
 C

子目录:

 AA
 BB
 CC

我可以使用 ftp.nlist() 列出目录 ['A', 'B', 'C']。我想得到 ['AA', 'BB', 'CC'] 作为我的输出。我已经尝试并进行了很多查找以找到解决方案/提示来执行此操作。

最佳答案

我知道这有点老了,但这里的答案可以让我省点力气,所以就在这里。我有点业余,所以这可能不是最有效的方法,但这是我编写的一个程序,用于获取 FTP 服务器上的所有目录。它会列出所有目录,无论它们在树下有多远。

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)

关于python - 使用 Python 列出 FTP 中所有子目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352484/

相关文章:

python - 如何将此 Python 代码更改为多进程而不是多线程?

python - 如何获得 Tkinter 小部件属性?

python - 颜色图不随 imshow() 改变

windows - Windows批量上传目录和文件到FTP

将一行分成四个单词组的 Pythonic 方法?

parsing - Grails处理FTP转储

.net - PowerShell:System.Net.WebClient.DownloadFile 不会下载从 ListDirectory 收集的文件

zend-framework2 - zend框架2在子目录中

asp.net-mvc - ASP.NET MVC - 在子目录中运行

python - 如果不使用python创建文件夹,如何检查目录中是否存在文件夹