简体   繁体   English

以Python递归列出FTP目录

[英]Recursively list FTP directories in Python

I'm having difficulty retrieving a list of directories on a remote FTP site. 我在远程FTP站点上检索目录列表时遇到了困难。 This answer does not work (I get no output, it appears to hang). 这个答案不起作用(我没有输出,它似乎挂起)。

Here's the simplest implementation I can think of - it should just print out the full path of every directory it finds: 这是我能想到的最简单的实现 - 它应该打印出它找到的每个目录的完整路径:

import ftplib

def ftp_walk(ftp):    
print 'Path:', ftp.pwd()
    dirs = ftp.nlst()
    for item in (path for path in dirs if path not in ('.', '..')):
        try:
            ftp.cwd(item)
            print 'Changed to', ftp.pwd()
            ftp_walk(ftp)
            ftp.cwd('..')
        except Exception, e:
            print item, e

ftp = ftplib.FTP('ftp.site.com')                                        
ftp.login('user', 'pass')
ftp.cwd('1')
ftp_walk(ftp)

My directory structure is: 我的目录结构是:

1/
 1-1/
   1-2/
 1-2/
 1-3/
 1-4

However, it only outputs the following. 但是,它只输出以下内容。 It suggests that the working directory is changed once to a new subdirectory, but when ftp_walk() is called with the new cwd, it doesn't go any further: 它建议将工作目录更改为一个新的子目录,但是当使用新的cwd调用ftp_walk()时,它不再进一步:

> Path: 1/
> Changed to 1-1/

ftp.login('user', 'pass')和构造函数之后,需要调用ftp.connect()

Well I suppose the user you are logging in has access to all that structure, because otherwise it will return an error and won't list that specific directory. 好吧,我想您登录的用户可以访问所有该结构,否则它将返回错误,并且不会列出该特定目录。

If you're getting an exception, please put it here. 如果您遇到异常,请将其放在此处。 Maybe you should try..finally your cwd so that it won't get lost. 也许你应该try..finally你的cwd,这样它就不会迷路。 Can I suggest: 我可以建议:

    try:
        ftp.cwd(item)
        print 'Changed to', ftp.pwd()
        try:
            ftp_walk(ftp)
        finally:
            ftp.cwd('..')
    except ftplib.error_perm, e:
        print item, e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM