我正在使用 FtpLib (Python) 从 ftp 服务器下载包含文件的文件夹.但我想在开始下载之前知道文件夹的大小.
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.
在文档中我找到了 FTP.size(filename)
但这仅适用于文件而不是文件夹...我可以遍历文件夹中的所有文件,但该文件夹可能包含子文件夹.
In the documentation I found FTP.size(filename)
but that's just for files and not for folders... I could loop through all the files in the folder but it is possible that the folder contains subfolders.
那么有人知道如何使用 FtpLib 获取文件夹的大小吗?
So does anyone know how to get the size of the folder using FtpLib?
经过反复试验,我找到了解决方案.
After some trial and error I found the solution.
它基于 Alex Thorntons 解决方案,但我记住可能存在子文件夹.当是文件夹时,ftp.cwd()
命令成功,递归调用函数.
It's based on Alex Thorntons solution but I kept in mind that there could be subfolders.
When it's a folder, the ftp.cwd()
command succeeds and the function is called recursively.
当 ftp.cwd()
命令抛出错误时,它是一个文件,我们可以获取文件大小.类型设置为I"(图像),这将强制二进制模式,因为 ftp.size()
命令在 ASCII 模式下是不允许的.
When the ftp.cwd()
command throws an error, it was a file and we can get the file size. The type is set to "I" (images), this forces binary mode since the ftp.size()
command is not allowed in ASCII mode.
def get_total_size(self, directory):
size = 0
for filename in self.ftp.nlst(directory):
try:
self.ftp.cwd(filename)
size += self.get_total_size(filename)
except:
self.ftp.voidcmd('TYPE I')
size += self.ftp.size(filename)
return size
这篇关于使用 FtpLib 获取文件夹大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!