問(wèn)題描述
我正在使用 FtpLib (Python) 從 ftp 服務(wù)器下載包含文件的文件夾.但我想在開始下載之前知道文件夾的大小.
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?
推薦答案
經(jīng)過(guò)反復(fù)試驗(yàn),我找到了解決方案.
After some trial and error I found the solution.
它基于 Alex Thorntons 解決方案,但我記住可能存在子文件夾.當(dāng)是文件夾時(shí),ftp.cwd()
命令成功,遞歸調(diào)用函數(shù).
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.
當(dāng) ftp.cwd()
命令拋出錯(cuò)誤時(shí),它是一個(gè)文件,我們可以獲取文件大小.類型設(shè)置為I"(圖像),這將強(qiáng)制二進(jìn)制模式,因?yàn)?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
這篇關(guān)于使用 FtpLib 獲取文件夾大小的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!