2017-07-30 113 views
0

的总规模,我试图找到与下面的脚本的FTP服务器的文件总大小:使用os.walk查找FTP服务器

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) 

一切工作,直到我尝试使用操作系统。走到FTP服务器上查找目录列表,使用ftp.cwd进入每个目录并将总大小添加到变量“size”。

当我调用print(size)时,结果为0,它应该是一个正整数。

我是否缺少os.wallk和ftp.pwd的组合?

+0

你需要使用ftp.cwd(os.path.join(root,x))吗? – AK47

+0

[使用FtpLib获取文件夹大小]的可能重复(https://stackoverflow.com/questions/22090001/get-folder-size-using-ftplib) –

回答

1

使用此函数可以使用ftp客户端获取目录的大小。

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 

您可以递归调用为每个目录 希望这有助于找到目录get_size_of_directory!

+0

嗨,这是否与根目录中的子目录一起工作? –

+0

您可以递归调用您在目录中找到的每个目录的get_size_of_directory。 –

+0

我更新了目录的功能。 –