ftplib checking if a file is a folder?

UberJumper picture UberJumper · Jul 6, 2009 · Viewed 17.6k times · Source

How can i check if a file on a remote ftp is a folder or not using ftplib?

Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?

Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)

What should i do?

Answer

Ceylan B. picture Ceylan B. · Oct 11, 2016

There are not "isdir" and "isfile" definitions in ftplib. If you don't have to use ftplib, i recommend you to use ftputil.

First of all you have to install ftputil package. To achive this, use this command: python -m pip install ftputil. After the installation, you can import the library to your code. I think it's enough explanation. So, let's go to the implementation:

import ftputil
with ftputil.FTPHost("host", "username", "password") as ftp_host:
    ftp_host.chdir("/directory/")   
    list = ftp_host.listdir(ftp_host.curdir)
    for fname in list:
        if ftp_host.path.isdir(fname):
            print(fname + " is a directory")
        else:
            print(fname + " is not a directory")