#!/usr/bin/env python
import os
import argparse
from collections import OrderedDict
import json
listdironly = lambda d: [os.path.join(d, o) for o in os.listdir(d) if os.path.isdir(os.path.join(d, o))]
listfileonly = lambda d: [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d, f))]
def get_file_list_recursively(d):
# get all files and dirs
subfiles = listfileonly(d)
subdirs = listdironly(d)
if len(subdirs) == 0:
return subfiles
else:
for subd in subdirs:
# print (subd)
subfiles = subfiles + get_file_list_recursively(subd)
return subfiles
"""
+-----------+---------+-------+------------+
| Names | Weights | Costs | Unit_Costs |
+===========+=========+=======+============+
| bar | 0.050 | 2 | 40 |
+-----------+---------+-------+------------+
| chocolate | 0.100 | 5 | 50 |
+-----------+---------+-------+------------+
| chips | 0.250 | 3 | 12 |
+-----------+---------+-------+------------+
OrderedDict{
'header': ['Names', 'Weights' ...],
'bar': [0.05, 2, 40 ...],
...
}
"""
def print_texttab(tab_kv):
import texttable as tt
tab = tt.Texttable()
for i, (k, v) in enumerate(tab_kv.items()):
if i == 0:
headings = tab_kv['header']
tab.header(headings)
tab.set_cols_align(["c"] * len(headings))
else:
if isinstance(v, (tuple, list)):
row_data = [k] + v
else:
row_data = [k, v]
tab.add_row(row_data)
tab_output = tab.draw()
print (tab_output)
def main(args):
curr_dirs = listdironly(args.dir)
count_dict = {os.path.basename(k):0 for k in curr_dirs}
for curr_d in curr_dirs:
curr_d_file_list = get_file_list_recursively(curr_d)
k_d = os.path.basename(curr_d)
count_dict[k_d] = len(curr_d_file_list)
count_rank = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)
# create table
table_rank = OrderedDict()
table_rank['header'] = ['Directory', 'File Count']
for count_item in count_rank:
table_rank[count_item[0]] = count_item[1]
print_texttab(table_rank)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Count files number.")
parser.add_argument('--dir', type=str, default='.')
args = parser.parse_args()
main(args)
显示效果如下:
+----------------------+------------+
| Directory | File Count |
+======================+============+
| Apps | 44254 |
+----------------------+------------+
| Pictures | 2349 |
+----------------------+------------+
就几行,我也懒得贴 gist 了 :)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.