I made it again for practicing Python.
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
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()
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