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

时间:2009-02-25 05:54:36

标签: python ftp

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

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

3 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:1)

如果FTP服务器支持MLSD命令,请查看that个答案,了解几个有用的课程(FTPDirectoryFTPTree)。

答案 2 :(得分:1)

另一种方法是假设一切都是目录并尝试改变它。如果成功,则它是一个目录,但如果这会抛出一个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
相关问题