Below is a Python script that traverses a given directory and creates a histogram of the file extensions found within the directory and its subdirectories. This script uses the os module to walk through the directory tree and the collections module to count the occurrences of each file extension.
import os
from collections import Counter
import matplotlib.pyplot as plt
def count_file_types(directory):
"""
Traverses through the given directory and counts the occurrences of each file extension.
:param directory: The directory path to traverse.
:return: A Counter object with file extensions and their counts.
"""
file_types = Counter()
for root, dirs, files in os.walk(directory):
for file in files:
_, ext = os.path.splitext(file)
if ext: # Only count files with an extension
file_types[ext.lower()] += 1
return file_types
def create_histogram(file_types):
"""
Creates a histogram for the given file types.
:param file_types: A Counter object with file extensions and their counts.
"""
# Sort the file types by count
sorted_file_types = dict(sorted(file_types.items(), key=lambda item: item[1], reverse=True))
# Create a histogram
plt.bar(sorted_file_types.keys(), sorted_file_types.values())
plt.xlabel('File Extensions')
plt.ylabel('Counts')
plt.title('Histogram of File Types')
plt.xticks(rotation=90) # Rotate the x-axis labels to show them more clearly
plt.tight_layout() # Adjust layout to prevent clipping of labels
# Show the histogram
plt.show()
if __name__ == '__main__':
# Ask the user for a directory path
directory_path = input("Enter the directory path to analyze: ")
if not os.path.exists(directory_path):
print("The directory does not exist. Please enter a valid directory path.")
else:
# Count file types in the directory
counts = count_file_types(directory_path)
# Check if any file was found
if counts:
# Create a histogram of the file types
create_histogram(counts)
else:
print("No files found in the specified directory.")
This script does the following:
- It defines a
count_file_types function that walks through the directory and counts file extensions using a Counter object.
- It defines a
create_histogram function that generates a bar chart representing the distribution of file types using matplotlib.
- In the
__main__ section, the script prompts the user for a directory path, checks whether the directory exists, and then processes the files in the directory to create a histogram.
To run this script, you'll need to have matplotlib installed. If you haven't installed matplotlib, you can install it using pip:
pip install matplotlib
After you have matplotlib installed, you can run the script, and it will prompt you to input the path to the directory you want to analyze. Once you provide a valid path, it will display a histogram of the file types found within that directory.