前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 统计 ftp 文件个数和

Python3 统计 ftp 文件个数和

作者头像
py3study
发布2020-01-03 16:38:36
7670
发布2020-01-03 16:38:36
举报
文章被收录于专栏:python3python3

【背景】

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

【环境】

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

【ftp_stat】

代码语言:javascript
复制
# 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()))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档