Problem 6.2
Count File Extensions
Write a program extcount.py
to count the number of files per extension. The program should take path to a directory as argument and print the count and extension for each available extension, sorted by the count. Files without any extension should be ignored.
$ python extcount.py files
4 py
3 txt
2 csv
1 yml
$ python extcount.py files/data
2 txt
1 csv
Solution
import sys
import os
from collections import Counter
path = sys.argv[1]
filenames = os.listdir(path)
extensions = [f.split(".")[-1] for f in filenames if "." in f]
for ext, count in Counter(extensions).most_common():
print(count, ext)