To create a Python script that traverses a given directory and generates a histogram of the file types, we can use libraries such as os for directory traversal and matplotlib for creating the graphical histogram.
First, ensure you have matplotlib installed. If not, you can install it using pip:
pip install matplotlib
Now, here's a Python script that accomplishes the task:
import os
import matplotlib.pyplot as plt
from collections import Counter
def get_file_extension(file):
_, ext = os.path.splitext(file)
return ext.lower()
def traverse_dir_and_count_filetypes(directory):
filetypes = []
for root, dirs, files in os.walk(directory):
for file in files:
ext = get_file_extension(file)
if ext: # Ignore files without an extension
filetypes.append(ext)
return Counter(filetypes)
def plot_histogram(filetype_counts):
# Sort by count
sorted_filetypes = sorted(filetype_counts.items(), key=lambda item: item[1], reverse=True)
extensions, counts = zip(*sorted_filetypes)
# Plot
plt.bar(extensions, counts)
plt.xlabel('File Types')
plt.ylabel('Frequency')
plt.title('Histogram of File Types in Directory')
plt.xticks(rotation=90) # Rotate x-axis labels to show them better
plt.tight_layout() # Adjust layout to prevent clipping of labels
plt.show()
if __name__ == "__main__":
directory = "D:\\vms"
if not os.path.exists(directory):
print(f"The directory {directory} does not exist.")
else:
filetype_counts = traverse_dir_and_count_filetypes(directory)
plot_histogram(filetype_counts)
Save this script as filetype_histogram.py and run it. The script will traverse the directory D:\vms, count the occurrences of each file extension, and then generate a bar histogram displaying the frequency of each file type.
Please note that the D:\vms directory must exist on your machine, and you should have the necessary permissions to read the files in that directory. Also, the script plots the histogram in a graphical window using matplotlib. If you run this script in a headless environment (like a server without a graphical user interface), you might encounter issues with displaying the plot.