Skip to content

Instantly share code, notes, and snippets.

@leninhasda
Created May 11, 2018 05:45
Show Gist options
  • Save leninhasda/9b83f1ea28de73812156e54e1d9090c7 to your computer and use it in GitHub Desktop.
Save leninhasda/9b83f1ea28de73812156e54e1d9090c7 to your computer and use it in GitHub Desktop.
Simple python script to count files in directory - v2
#!/usr/bin/env python3
import argparse, os, sys
from os.path import isdir, join, getsize
from pprint import pprint
def main():
# initiate the parser
parser = argparse.ArgumentParser(description="count files in given directory")
parser.add_argument("-d", "--dir", help="directory path(s) to count files", nargs='+')
parser.add_argument("-s", "--size", help="display total size of directory", action="store_true")
parser.add_argument("-v", "--verbose", help="displays all the files list", action="store_true")
# parse
args = parser.parse_args()
# by default count the curernt directory
dir_list = ["./"]
if args.dir and len(args.dir) > 0:
dir_list = args.dir
for dir_name in dir_list:
if not isdir(dir_name):
print("\"{}\" is not a directory!".format(dir_name))
continue
dir_walk(dir_name, args.size, args.verbose)
def dir_walk(dir_name, is_size = False, is_verbose = False):
total = {
"file-count": 0,
"size": 0,
"files": []
}
for root, dirs, files in os.walk(dir_name):
total["file-count"] = total["file-count"] + len(files)
total["size"] = total["size"] + sum(getsize(join(root, name)) for name in files)
total["files"] = total["files"] + [join(root, f) for f in files]
if dir_name in ["./", "."]:
dir_name = "current"
print("\nTotal {} files in {} directory".format(total["file-count"], dir_name))
if is_size:
print("Total size: {}".format(sizeof_fmt(total["size"])))
if is_verbose:
print("Files list:")
for file in total["files"]:
print(file)
def sizeof_fmt(num):
# Thanks to Fred Cirera for this
# https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
if __name__ == '__main__':
main()
@leninhasda
Copy link
Author

Usage:
Copy the content and save in a file. (ex: count-files.py or just download it)
Now you should be able to run it like this:

python count-files.py  # current directory (default)
python count-files.py -d /home/lenin/downloads /home/lenin/music # count files in downloads and music directory in /home/lenin

# or do this
chmod +x count-files.py
sudo mv /usr/local/bin/count-files

# then from anywhere in terminal
count-files -d ~/Downloads  -s # count files in Download directory, -s to display total size as well

25-count-files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment