Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ftplib checking if a file is a folder?

Tags:

python

ftp

ftplib

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?

like image 887
UberJumper Avatar asked Jul 06 '09 17:07

UberJumper


1 Answers

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")
like image 53
Ceylan B. Avatar answered Sep 26 '22 00:09

Ceylan B.