Get folder size using FtpLib

前端 未结 3 1107
说谎
说谎 2021-01-03 11:17

I\'m using FtpLib (Python) to download a folder with files from an ftp server. But I want to know the size of the folder before I start downloading it.

In the docume

3条回答
  •  醉梦人生
    2021-01-03 12:08

    Frederik Voordeckers' solution didn't work for me. When the method is called recursively, when dealing with a structure of subfolders, it raises the error 550 directory/.../sub_directory: No such file or directory.
    I did modify his original code, by deleting the "self-declarations", since I did not use the method inside a class. This might have caused the error. I don't know.

    Here is my solution:

    def get_total_size(ftp_dir):
        size = 0
        parent_dir = ftp.pwd() # get the current directory
        for filename in ftp.nlst(ftp_dir):
            # (don't forget to import os)
            path = os.path.join(parent_dir, filename) # keeps recursively track of the path
            try:
                ftp.cwd(path)
                size += get_total_size(path)
                ftp.cwd(parent_dir)
            except:
                ftp.voidcmd('TYPE I')
                size += ftp.size(path)
        return size
    

    Should work like a charm for everyone.

提交回复
热议问题