A Python CLI tool that counts and displays the number of files per extension in a specified directory.
- Recursive scanning: Counts files in all subdirectories
- Extension tracking: Identifies files by their extension
- Formatted output: Displays results in a clean, readable table format
- Statistics: Shows count and percentage breakdown for each extension
- Error handling: Gracefully handles permission errors and invalid paths
- No extension support: Tracks files without extensions
- Python 3.6 or higher
- Standard library only (no external dependencies)
No installation required! Simply download the script:
curl -O https://raw.githubusercontent.com/sumanth-0/100LinesOfPythonCode/main/%231005_FILE_EXTENSION_COUNTER/file_extension_counter.pyCount files in the current directory:
python file_extension_counter.pyCount files in a specific directory:
python file_extension_counter.py /path/to/directory# Count files in Documents folder
python file_extension_counter.py ~/Documents
# Count files in current project
python file_extension_counter.py .
# Count files in a specific path
python file_extension_counter.py /Users/username/projectsScanning directory: /Users/username/projects...
============================================================
File Extension Count Report
Directory: /Users/username/projects
============================================================
Extension Count Percentage
-------------------- ---------- ------------
.py 45 45.0%
.md 20 20.0%
.txt 15 15.0%
.json 10 10.0%
(no extension) 10 10.0%
------------------------------------------------------------
Total Files: 100
============================================================
- Path Validation: Checks if the provided path exists and is a directory
- Recursive Scan: Uses
pathlib.Path.rglob()to find all files recursively - Extension Extraction: Captures each file's extension using
Path.suffix - Counting: Aggregates extensions using Python's
Counterfrom collections - Display: Formats and displays results sorted by count (descending)
The tool handles common errors gracefully:
- Directory not found: Displays clear error message
- Permission denied: Catches and reports permission issues
- Invalid path: Validates that the path is a directory
- General exceptions: Catches and displays unexpected errors
count_extensions(directory): Scans directory and counts file extensionsdisplay_results(extension_counts, directory): Formats and displays resultsmain(): Entry point, handles command-line arguments
This project is part of the 100LinesOfPythonCode repository. Contributions are welcome!
For issue #1005 - File Extension Counter
This project follows the license of the parent repository.
Contributed to 100LinesOfPythonCode - Issue #1005