I made a program to check the size of a file in Python


I made it again for practicing Python.

Software description

Outputs the absolute path and size of a file with a capacity larger than the set capacity in the terminal. The options are as follows

---- start: You can set the start point of file search ---- sort: Output from large files ---- more: You can set the output reference capacity ---- grep: Only paths containing the specified string can be displayed


Ubuntu18.04LTS Python3.6.9 vim

Source code

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
            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):
            elif os.path.isdir(content):

        return path_list, dir_list

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

    def get_deeper(self, dir_list):
        for dire in dir_list:
            if os.path.islink(dire):

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

    def search(self, word):
        for i in self.grep:
            if word.find(i) >= 0:
                return word
    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:
            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:
        except FileNotFoundError:
            print(args.start , 'is not file or directory.')

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

if __name__ == '__main__':

in conclusion

I will add various functions at any time, such as a function to display the last modified date of the file and a function to save the result to a CSV file.

Recommended Posts

I made a program to check the size of a file in Python
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
I made a function to check the model of DCGAN
I made a payroll program in Python!
I created a script to check if English is entered in the specified position of the JSON file in Python.
I made a Caesar cryptographic program in Python.
Test & Debug Tips: Create a file of the specified size in Python
I made a function to see the movement of a two-dimensional array (Python)
I made a prime number generation program in Python
I want to randomly sample a file in Python
I made a prime number generation program in Python 2
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
Various ways to read the last line of a csv file in Python
I made an appdo command to execute a command in the context of the app
I made a script to record the active window using win32gui of Python
Change the standard output destination to a file in Python
[Note] Import of a file in the parent directory in Python
How to check in Python if one of the elements of a list is in another list
Check the behavior of destructor in Python
I made a configuration file with Python
I made a program to solve (hint) Saizeriya's spot the difference
How to determine the existence of a selenium element in Python
I made a program that solves the spot the difference in seconds
I wrote the code to write the code of Brainf * ck in python
Read a file in Python with a relative path from the program
I made a library that adds docstring to a Python stub file.
I made a command to display a colorful calendar in the terminal
[Python] A program that rotates the contents of the list to the left
I made a class to get the analysis result by MeCab in ndarray with python
A program that automatically resizes the iOS app icon to the required image size in Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I made a function to crop the image of python openCV, so please use it.
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I made a python dictionary file for Neocomplete
I made a web application in Python that converts Markdown to HTML
[Python] A program that calculates the number of socks to be paired
Get the caller of a function in Python
I want to create a window in Python
How to create a JSON file in Python
Make a copy of the list in Python
(Python Selenium) I want to check the settings of the download destination of WebDriver
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I want to sort a list in the order of other lists
The file name was bad in Python and I was addicted to import
I want to color a part of an Excel string in Python
I made a script in python to convert .md files to Scrapbox format
I made a function to check if the webhook is received in Lambda for the time being
Output in the form of a python array
I made a mistake in fetching the hierarchy with MultiIndex of pandas
I tried to display the altitude value of DTM in a graph
I want to write to a file with Python
Python: I want to measure the processing time of a function neatly
I tried to implement a card game of playing cards in Python
I want to display the progress in Python!
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
I tried to open the latest data of the Excel file managed by date in the folder with Python
I made a tool to estimate the execution time of cron (+ PyPI debut)
How to pass the execution result of a shell command in a list in Python
How to mention a user group in slack notification, how to check the id of the user group