[英]List with all the files in directories &subdirectories with path (Python)
[英]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.