Simple Python Code: Directory & File Structure Listing with Python and Tkinter
This Python code is a great starting point for creating more advanced search and analytics tools. By understanding the directory structure, you can build features like file searching, metadata extraction, and more.
The code is easy to understand and modify, making it accessible for developers of all skill levels. The recursive function efficiently lists all directories and files, providing a clear view of the directory structure. The Tkinter GUI allows for easy directory selection and dynamic resizing, enhancing user experience.
import os
import tkinter as tk
from tkinter import filedialog, scrolledtext
def list_files_and_directories(path, indent=""):
try:
items = os.listdir(path)
except PermissionError:
text_box.insert(tk.END, f"{indent}Permission Denied: {path}\n")
return
for item in items:
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
text_box.insert(tk.END, f"{indent}?? {item}\n")
list_files_and_directories(item_path, indent + " ")
else:
text_box.insert(tk.END, f"{indent}?? {item}\n")
def select_directory():
directory = filedialog.askdirectory()
if directory:
# Clear the text box
text_box.delete(1.0, tk.END)
# Print the directory structure
text_box.insert(tk.END, f"Root Directory: {directory}\n")
list_files_and_directories(directory)
# Create the main window
root = tk.Tk()
root.title("Directory and File Treeview")
# Configure grid layout
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
# Create a button to select the directory
select_button = tk.Button(root, text="Select Directory", command=select_directory)
select_button.grid(row=0, column=0, pady=10, padx=10, sticky='ew')
# Create a scrolled text box to display the output
text_box = scrolledtext.ScrolledText(root, width=80, height=20)
text_box.grid(row=1, column=0, pady=10, padx=10, sticky='nsew')
# Run the application
root.mainloop()
How It Works:
领英推荐
Happy coding!
Neven Dujmovic, October 2024
#Python #Tkinter