Python列出FTP当前目录中的所有文件和子目录,并统计大小
import ftplib
# python3 ftp_get_dir_size.py
# 连接到FTP服务器
ftp = ftplib.FTP('168.8.2.1')
ftp.login(user='use', passwd='pwd')
# 列出当前目录中的所有文件和子目录
def get_dir_size(path):
size = 0
# 进入根目录
ftp.cwd(path)
for fileinfo in ftp.mlsd(path):
# print(fileinfo)
filename = fileinfo[0]
filetype = fileinfo[1]['type']
# print (filename,filetype)
if filetype == 'file':
size += int(fileinfo[1]['size'])
elif filetype == 'dir':
fullpath = path + '/' + fileinfo[0]
size += get_dir_size(fullpath)
#print(path, format(size, ","))
if size > 1000000000:
print(path, "=", format(size, ","))
return size
size = get_dir_size('/')
print("totalsize:", format(size, ","))