【问题标题】:Determine if a listing is a directory or file in Python over FTP通过 FTP 确定列表是否是 Python 中的目录或文件
【发布时间】:2010-10-09 18:00:19
【问题描述】:

Python 有一个标准库模块ftplib 来运行 FTP 通信。它有两种获取目录内容列表的方法。一个,FTP.nlst(),将返回一个目录的内容列表,给定一个目录名称作为参数。 (如果给定文件名,它将返回文件名。)这是一种列出目录内容的可靠方法,但不提供任何指示列表中的每个项目是文件还是目录。另一种方法是FTP.dir(),它以字符串格式列出目录的目录内容,作为参数(或文件属性,给定文件名)。

根据a previous question on Stack Overflow,解析dir()的结果可能很脆弱(不同的服务器可能返回不同的字符串)。不过,我正在寻找某种方法来仅列出通过 FTP 包含在另一个目录中的目录。据我所知,在字符串的权限部分抓取d 是我想出的唯一解决方案,但我想我不能保证权限会出现在不同权限之间的同一个地方服务器。是否有更强大的解决方案来通过 FTP 识别目录?

【问题讨论】:

    标签: python ftp


    【解决方案1】:

    不幸的是,FTP 没有仅列出文件夹的命令,因此解析从 ftp.dir() 获得的结果将是“最好的”。

    一个简单的应用程序,假设来自 ls(不是 windows ftp)的标准结果

    from ftplib import FTP
    
    ftp = FTP(host, user, passwd)
    for r in ftp.dir():
        if r.upper().startswith('D'):
            print r[58:]  # Starting point
    

    Standard FTP Commands

    Custom FTP Commands

    【讨论】:

      【解决方案2】:

      如果 FTP 服务器支持MLSD 命令,请查看that 答案以获取几个有用的类(FTPDirectoryFTPTree)。

      【讨论】:

        【解决方案3】:

        另一种方法是假设所有内容都是一个目录并尝试更改为它。如果成功,它是一个目录,但如果它抛出一个 ftplib.error_perm 它可能是一个文件。您可以先捕获然后捕获异常。当然,这并不是最安全的,但也不是为前导 'd' 解析疯狂的字符串。

        例子

        def processRecursive(ftp,directory):
            ftp.cwd(directory)
            #put whatever you want to do in each directory here
            #when you have called processRecursive with a file, 
            #the command above will fail and you will return
        
        
            #get the files and directories contained in the current directory
            filenames = []
            ftp.retrlines('NLST',filenames.append)
            for name in filenames:
                try:
                    processRecursive(ftp,name)
                except ftplib.error_perm:
                    #put whatever you want to do with files here
        
            #put whatever you want to do after processing the files 
            #and sub-directories of a directory here
        

        【讨论】:

          猜你喜欢
          • 2012-05-28
          • 2011-11-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-14
          相关资源
          最近更新 更多