这是一个幼稚且缓慢的实现。这很慢,因为它尝试CWD到每个目录条目以确定它是目录还是文件,但这是可行的。可以通过解析LIST命令输出来优化它,但这在很大程度上取决于服务器实现。
import ftplibdef traverse(ftp, depth=0): """ return a recursive listing of an ftp server contents (starting from the current directory) listing is returned as a recursive dictionary, where each key contains a contents of the subdirectory or None if it corresponds to a file. @param ftp: ftplib.FTP object """ if depth > 10: return ['depth > 10'] level = {} for entry in (path for path in ftp.nlst() if path not in ('.', '..')): try: ftp.cwd(entry) level[entry] = traverse(ftp, depth+1) ftp.cwd('..') except ftplib.error_perm: level[entry] = None return leveldef main(): ftp = ftplib.FTP("localhost") ftp.connect() ftp.login() ftp.set_pasv(True) print traverse(ftp)if __name__ == '__main__': main()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)