簡體   English   中英

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

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

我是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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM