繁体   English   中英

确定列表是否是 Python 中 FTP 中的目录或文件

[英]Determine if a listing is a directory or file in Python over FTP

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

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

不幸的是 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

标准 FTP 命令

自定义 FTP 命令

另一种方法是假设所有内容都是一个目录并尝试更改为它。 如果成功,它是一个目录,但如果这抛出一个 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

如果 FTP 服务器支持MLSD命令,那么请检查几个有用类( FTPDirectoryFTPTree答案。

暂无
暂无

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

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