使用FtpLib获取文件夹大小 [英] Get folder size using FtpLib
问题描述
我使用FtpLib(Python)从ftp服务器下载包含文件的文件夹。但是我想在开始下载文件夹之前知道文件夹的大小。
在文档中我发现 FTP.size(filename)
那么有谁知道如何使用FtpLib获取文件夹的大小?
解决方案 解决方案。
它基于Alex Thorntons解决方案,但我一直记住可能有子文件夹。
当它是一个文件夹时, ftp.cwd()
命令成功并且递归地调用该函数。
<当
ftp.cwd()
命令引发错误时,它是一个文件,我们可以获取文件大小。由于 ftp.size()
命令在ASCII模式下是不允许的,因此该类型设置为I(图像),因此强制使用二进制模式。 def get_total_size(self,directory):
size = 0
用于self.ftp.nlst(目录)中的文件名:
try:
self.ftp.cwd(文件名)
size + = self.get_total_size(文件名)
除外:
self.ftp.voidcmd('TYPE I' )
size + = self.ftp.size(filename)
返回大小
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 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.
So does anyone know how to get the size of the folder using FtpLib?
After some trial and error I found the solution.
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.
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获取文件夹大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!