Traversing FTP listing

前端 未结 5 1743
广开言路
广开言路 2020-12-18 03:39

I am trying to to get all directories\' name from an FTP server and store them in hierarchical order in a multidimensional list or dict

So for example, a server that

5条回答
  •  清歌不尽
    2020-12-18 04:27

    Here is a naive and slow implementation. It is slow because it tries to CWD to each directory entry to determine if it is a directory or a file, but this works. One could optimize it by parsing LIST command output, but this is strongly server-implementation dependent.

    import ftplib
    
    def 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 level
    
    def main():
        ftp = ftplib.FTP("localhost")
        ftp.connect()
        ftp.login()
        ftp.set_pasv(True)
    
        print traverse(ftp)
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题