Traversing FTP listing

前端 未结 5 1718
广开言路
广开言路 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:12

    Here's a first draft of a Python 3 script that worked for me. It's much faster than calling cwd(). Pass in server, port, directory, username, and password as arguments. I left output as a list as an exercise for the reader.

    import ftplib
    import sys
    
    def ftp_walk(ftp, dir):
        dirs = []
        nondirs = []
        for item in ftp.mlsd(dir):
            if item[1]['type'] == 'dir':
                dirs.append(item[0])
            else:
                nondirs.append(item[0])
        if nondirs:
            print()
            print('{}:'.format(dir))
            print('\n'.join(sorted(nondirs)))
        else:
            # print(dir, 'is empty')
            pass
        for subdir in sorted(dirs):
            ftp_walk(ftp, '{}/{}'.format(dir, subdir))
    
    ftp = ftplib.FTP()
    ftp.connect(sys.argv[1], int(sys.argv[2]))
    ftp.login(sys.argv[4], sys.argv[5])
    ftp_walk(ftp, sys.argv[3])
    

提交回复
热议问题