Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@yoshige

Pythonでファイルの容量を調べるプログラムを作った

More than 1 year has passed since last update.

はじめに

今回もPythonの練習のために作りました。

ソフトウェアの説明

設定した容量以上の容量を持つファイルの絶対パスとサイズをターミナルで出力します。
オプションは以下の通り

  • --start: ファイル探索のスタート地点を設定できる
  • --sort: サイズの大きいファイルから出力されるようになる
  • --more: 出力の基準となる容量をを設定できる
  • --grep: 指定した文字列を含むパスのみ表示することができる

環境

Ubuntu18.04LTS
Python3.6.9
vim

ソースコード

import argparse
import os


class Measure:
    def __init__(self, sort=None, more=None, grep=None):
        self.sort = sort

        if more is None:
            self.more = 1024 * 1024
        else:
            self.more = more

        self.grep = grep
        self.result = []

    def get_list(self):
        path_list = []
        dir_list = []
        for content in os.listdir():
            if os.path.isfile(content):
                path_list.append(content)
            elif os.path.isdir(content):
                dir_list.append(content)

        return path_list, dir_list

    def measure(self, path_list):
        for path in path_list:
            if os.path.getsize(path) > self.more:
                self.result.append(
                        (os.path.abspath(path), os.path.getsize(path))
                    )

    def get_deeper(self, dir_list):
        for dire in dir_list:
            if os.path.islink(dire):
                continue
            os.chdir(dire)
            self.main()
            os.chdir('../')

    def main(self):
        path_list, dir_list = self.get_list()
        self.measure(path_list)
        self.get_deeper(dir_list)

    def search(self, word):
        for i in self.grep:
            if word.find(i) >= 0:
                return word
            else:
                return

    def convert_unit(self, capacity):
        unit = {0: 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
        count = 0
        while capacity // 1024:
            capacity /= 1024
            count += 1

        capacity = round(capacity)
        capacity = str(capacity) + unit[count]
        return capacity 

    def show_result(self):
        if self.sort:
            self.result = sorted(self.result, key=lambda z: z[1], reverse=True)
        for path, capacity in self.result:
            if self.grep:
                path = self.search(path)
            if path is None:
                continue
            capacity = self.convert_unit(capacity)
            print(path, capacity)


def get_parser():
    parser = argparse.ArgumentParser(description='search file\'s capacity')

    parser.add_argument('--start', help='')
    parser.add_argument('--sort', action='store_true', help='')
    parser.add_argument('--more', type=int, help='')
    parser.add_argument('--grep', nargs='*', help='')

    return parser.parse_args()


def cli():
    args = get_parser()

    if args.start:
        try:
            os.chdir(args.start)
        except FileNotFoundError:
            print(args.start , 'is not file or directory.')
            return

    m = Measure(args.sort, more=args.more, grep=args.grep)
    m.main()
    m.show_result()


if __name__ == '__main__':
    cli()

おわりに

ファイルの最終更新日を表示する機能や結果をCSVファイルに保存する機能など、随時いろんな機能を追加しようと思います。

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?