Count File Extensions
Write file_extension_counts(paths) that takes a list of file paths (text, with / separators) and returns a dictionary from extension to the number of files with that extension.
- The extension is the part from the last dot of the file name, in lower case, including the dot:
"photo.JPG"counts under".jpg";"archive.tar.gz"counts under".gz". - Files with no extension are counted under
"(none)". A name that only starts with a dot, such as".gitignore", has no extension.
Understand the problem
See what pathlib knows about names.
What is PurePosixPath("src/archive.tar.gz").suffix?
".tar.gz"".gz""gz"
.suffix is the last extension including its dot. (.suffixes gives the whole list [".tar", ".gz"].) For this task the last one is what we want.
What is PurePosixPath("home/.gitignore").suffix?
".gitignore"""(empty): a leading dot is part of the name, not an extension".git"
pathlib treats a name that only starts with a dot as a hidden file with no extension, so .suffix is empty. A hand-written split(".") would get this wrong.
Write the solution
Return the dictionary of counts.
def file_extension_counts(paths):
# Write your code here.
pass
Hint 1: a question to ask yourself
Which standard-library class understands file names, so you do not have to find the dot yourself?
Hint 2: the shape of the answer
For each path make PurePosixPath(path) and take .suffix.lower(); if it is empty use "(none)". Count with a Counter and return dict(counter).
Reflect
Solution
from collections import Counter
from pathlib import PurePosixPath
def file_extension_counts(paths):
counts = Counter()
for path in paths:
extension = PurePosixPath(path).suffix.lower() or "(none)"
counts[extension] += 1
return dict(counts)
Another way: os.path.splitext
import os.path
from collections import Counter
def file_extension_counts(paths):
counts = Counter(os.path.splitext(p)[1].lower() or "(none)" for p in paths)
return dict(counts)
What this tests: pathlib.PurePosixPath (.suffix, .name, .stem), os.path.splitext, Counter and or for a default.
Do not split paths by hand. path.split(".")[-1] fails for "Makefile" (returns the whole name) and for "v1.2/readme" (the dot is in the folder). pathlib and os.path know the rules.
PurePath versus Path: PurePosixPath only manipulates names and never touches the disk, which is what you want here and makes it testable. Path can also read and list files.
The or default works because an empty suffix is falsy. (Compare the parse_int problem: or is only safe when the "real" value can never be falsy.)
What an interviewer might ask next: Group the files by extension instead of counting them. (A dictionary of lists: setdefault(ext, []).append(path).)
VISIBLE = 3
CASES = [
((['a.txt', 'b.txt', 'c.py'],), {'.txt': 2, '.py': 1}, 'a few files'),
((['photo.JPG', 'pic.jpg'],), {'.jpg': 2}, 'capital letters'),
((['archive.tar.gz'],), {'.gz': 1}, 'a double extension'),
(([],), {}, 'no files'),
((['Makefile', 'LICENSE'],), {'(none)': 2}, 'no extension'),
((['home/.gitignore', '.bashrc'],), {'(none)': 2}, 'hidden files have no extension'),
((['v1.2/readme', 'v1.2/notes.md'],), {'(none)': 1, '.md': 1}, 'a dot in a folder name'),
((['dir/sub/file.name.PDF'],), {'.pdf': 1}, 'dots in the name'),
]