I'm new to Python and I'm trying to list all the files in all the sub-directories from an FTP. The FTP, as usual, is in this format.
我是Python新手,我试图从FTP列出所有子目录中的所有文件。像往常一样,FTP采用这种格式。
A
B
C
Subdirectories :
AA
BB
CC
I could list the directories ['A', 'B', 'C']
using ftp.nlist()
. I'd like to get ['AA', 'BB', 'CC']
as my output. I've tried and looked up a lot to find a solution/hint to do this.
我可以使用ftp.nlist()列出目录['A','B','C']。我想把['AA','BB','CC']作为我的输出。我已经尝试并查找了很多,以找到解决方案/提示来做到这一点。
1 个解决方案
#1
2
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. It will list all directories no matter how far they are down the tree.
我知道这有点老了,但这里的答案本可以省去一些努力,所以现在就是这样。我有点像业余爱好者,所以这可能不是最有效的方式,但这是我写的一个程序来获取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)
#1
2
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. It will list all directories no matter how far they are down the tree.
我知道这有点老了,但这里的答案本可以省去一些努力,所以现在就是这样。我有点像业余爱好者,所以这可能不是最有效的方式,但这是我写的一个程序来获取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)