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

后端 未结 3 786
遥遥无期
遥遥无期 2020-12-19 08:40

Python has a standard library module ftplib to run FTP communications. It has two means of getting a listing of directory contents. One, FTP.nlst()

相关标签:
3条回答
  • 2020-12-19 09:00

    Unfortunately FTP doesn't have a command to list just folders so parsing the results you get from ftp.dir() would be 'best'.

    A simple app assuming a standard result from ls (not a 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

    0 讨论(0)
  • 2020-12-19 09:04

    If the FTP server supports the MLSD command, then please check that answer for a couple of useful classes (FTPDirectory and FTPTree).

    0 讨论(0)
  • 2020-12-19 09:17

    Another way is to assume everything is a directory and try and change into it. If this succeeds it is a directory, but if this throws an ftplib.error_perm it is probably a file. You can catch then catch the exception. Sure, this isn't really the safest, but neither is parsing the crazy string for leading 'd's.

    Example

    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
    
    0 讨论(0)
提交回复
热议问题