[Tutor] ftp recursive directory function doesn't work.

mhysnm1964 at gmail.com mhysnm1964 at gmail.com
Wed Dec 14 03:47:55 EST 2022


All,

 

I am trying to navigate a ftp server directory structure to see how big the
directory actually is. The function recursively goes through the
directories. When I pass the first if test calling the os object. I get a
file not found error and it breaks. Everything in the first level directory
are directories. I cannot work out what is going wrong.

 

from ftplib import FTP

import os

 

def get_size(ftp, directory):

    size = 0

    ftp.cwd(directory) <ftp://ftp.cwd(directory)> 

    files = ftp.nlst(b <ftp://ftp.nlst(b>  )

    for file in files:

        if os.path.isdir(file):

            size += get_size(ftp, file)

        else:

            size += ftp.size(file) <ftp://ftp.size(file)> 

    return size

 

ftp = FTP('ftp.example.com')

username = 'a name'

pwd = 'a password'

ftp.login(user <ftp://ftp.login(user>  = username, passwd = pwd)

    

starting_dir = '/dvds/'

 

size = get_size(ftp, starting_dir)

print('Total size of directory and subdirectories:', size)

 

This is not a school exercise. I am trying to work how long it will take
backup a directory.

 

Sean 



More information about the Tutor mailing list