Search code examples
pythonftppython-os

Using os.walk to find total size of FTP server


I am trying to find the total file size of an ftp server with the following script:

import os
import ftplib
from os.path import join, getsize

serveradd = ("an.ftpserver.co.uk")          # Define the ftp server

print("Logging in to "+serveradd+"\n")

top = os.getcwd()                                       # Define the current directory

filelist = []

for (root, dirs, files) in os.walk(top):   # Get list of files in current directory
    filelist.extend(files)
    break

dirname = os.path.relpath(".","..")                     # Get the current directory name

ftp = ftplib.FTP(serveradd)

try:                                                    # Log in to FTP server
    ftp.login("username", "password")
except:
    "Failed to log in..."

ftp.cwd('data/TVT/')                                    # CD into the TVT folder

print("Contents of "+serveradd+"/"+ftp.pwd()+":")

ftp.retrlines("LIST")                                   # List directories on FTP server

print("\n")

print(ftp.pwd())

print(serveradd+ftp.pwd())

size = 0

for (root, dirs, files) in os.walk(ftp.pwd()):
    for x in dirs:
        try:
            ftp.cwd(x)
            size += ftp.size(".")
            ftp.cwd("..")
        except ftplib.error_perm:
            pass
print(size)

Everything is working up until I try to use os.walk to find the list of directories on the FTP server, use ftp.cwd to go into each directory and add the total size to the variable "size".

When I call print(size) the result is 0, when it should be a positive integer.

Am I missing something with the combination of os.wallk and ftp.pwd?


Solution

  • Use this function to fetch the size of directory using ftp client.

    def get_size_of_directory(ftp, directory):
        size = 0
        for name in ftp.nlst(directory):
            try:
                ftp.cwd(name)
                size += get_size_of_directory(name)
            except:
                ftp.voidcmd('TYPE I')
                size += ftp.size(name)
        return size
    

    You can recursively call the get_size_of_directory for each directory you find in the directory Hope this helps !!