Python3 统计 ftp 文件个数和大小

发布时间:2020-06-20 16:11:47 作者:RQSLT
来源:网络 阅读:2480

【背景】

    本程序遍历 ftp 目录,列出单个文件大小,统计目录个数、文件个数、文件总大小。目的是在批量下载 FTP 文件时,不严格的验证下载结果的正确性。 


【环境】

    Windows10 下 Python 3.6.5,第三方包 ftputil 3.4。


【ftp_stat】

# encoding: utf-8
# author: walker
# date: 2018-10-12
# summary: 遍历 ftp 目录,列出单个文件大小,统计目录个数、文件个数、文件总大小。

import time
import ftputil

FtpHost = r'ftp.ncbi.nlm.nih.gov'  # FTP 主机
SubDir = r'/pubmed/baseline/'   # 最后的斜线有无不影响,根目录用单斜线即可
FtpUser = r'anonymous'        
FtpPwd = r'' 
FtpEncoding = r'utf-8'

def Main():
    r"""
        遍历 ftp 目录,列出单个文件大小,统计目录个数、文件个数、文件总大小。
    """
    fileCnt = 0
    fileSize = 0
    dirCnt = 0
    with ftputil.FTPHost(host=FtpHost, user=FtpUser, passwd=FtpPwd) as host:
        for parent, dirnames, filenames in host.walk(SubDir):
            for filename in filenames:
                fileCnt += 1
                pathfile = host.path.join(parent, filename)
                singleFileSize = host.path.getsize(pathfile)
                fileSize += singleFileSize
                print('\tfile: %s, %d bytes' %
                      (pathfile.encode('latin-1').decode(FtpEncoding), singleFileSize))

            for dirname in dirnames:
                dirCnt += 1
                pathdir = host.path.join(parent, dirname)
                print('\tdir: %s' % pathdir.encode(
                    'latin-1').decode(FtpEncoding))

            print('fileCnt: %d, fileSize: %d B/%.2f KB/%.2f MB/%.2f GB, dirCnt: %d'
                  % (fileCnt, fileSize, fileSize/1024, fileSize/1024/1024, fileSize/1024/1024/1024, dirCnt))

    print('fileCnt: %d, fileSize: %d B/%.2f KB/%.2f MB/%.2f GB, dirCnt: %d'
          % (fileCnt, fileSize, fileSize/1024, fileSize/1024/1024, fileSize/1024/1024/1024, dirCnt))


if __name__ == '__main__':
    Main()
    print('current time: %s\n'
          % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))


【相关阅读】


*** walker ***


推荐阅读:
  1. Python3 备份 MySQL/MariaDB(本地+FTP)
  2. Python3快速入门(十二)——NumPy

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ftputil 数和大小

上一篇:file文件操作

下一篇:php中有哪些定义常量的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》