def start_grouping():
dir_path = dir_label.cget("text")
if os.path.isdir(dir_path):
group_files_by_segment(dir_path)
def group_files_by_segment(dir_path):
compare_length = compare_slider.get()
files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
grouped_files = defaultdict(list)
code
for file in files:
if ':' in file:
segment = file.split(':', 1)[1].strip()
else:
segment = file.strip()
comparison_key = segment[:compare_length]
# Add the file to a group with a shared comparison key
grouped_files[comparison_key].append(file)
folder_listbox.delete(0, tk.END)
sorted_grouped_keys = sorted(grouped_files) # Sort keys to display
for group_name in sorted_grouped_keys:
folder_listbox.insert(tk.END, group_name)
folder_listbox.grouped_files = grouped_files
def show_folder_content(event):
widget = event.widget
if not widget.curselection():
return
index = widget.curselection()[0]
group_name = widget.get(index)
grouped_files = getattr(folder_listbox, 'grouped_files', {})
code
filenames_listbox.delete(0, tk.END)
for file in grouped_files.get(group_name, []):
filenames_listbox.insert(tk.END, file)
def rename_folder(event):
widget = event.widget
if not widget.curselection():
return
index = widget.curselection()[0]
old_name = widget.get(index)
code
new_name = simpledialog.askstring("Rename Folder", f"Enter new name for {old_name}:")
if new_name:
grouped_files = getattr(folder_listbox, 'grouped_files', {})
if old_name in grouped_files:
grouped_files[new_name] = grouped_files.pop(old_name)
widget.delete(index)
widget.insert(index, new_name)
for folder_name, file_list in grouped_files.items():
folder_path = os.path.join(dir_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
for f in file_list:
src_file = os.path.join(dir_path, f)
dest_file = os.path.join(folder_path, f)
shutil.move(src_file, dest_file)
Can you explain this script to me using an example?
Sure! Let's walk through your Python script step-by-step using a concrete example. This will help you understand how each part of the script operates and how they work together to group and organize files in a directory.
Overview
Your script provides a graphical user interface (GUI) that allows users to:
Select a Directory: Choose a folder containing files to be organized.
Group Files: Automatically group files based on a specified segment of their names.
View Groups and Files: Display the groups and the files within each group.
Rename Groups: Optionally rename the groups.
Apply Changes: Create folders for each group and move the corresponding files into these folders.
Let's break down each component with an example.
Example Scenario
Imagine you have a directory containing the following files:
Functionality: Opens a dialog that allows the user to select a directory.
Example: You select the directory containing the example files listed above. The selected path is displayed in dir_label.
3. Starting the Grouping Process
python
def start_grouping():
dir_path = dir_label.cget("text")
if os.path.isdir(dir_path):
group_files_by_segment(dir_path)
Functionality: Checks if a valid directory is selected and initiates the grouping process by calling group_files_by_segment.
4. Grouping Files by Segment
python
def group_files_by_segment(dir_path):
compare_length = compare_slider.get()
files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
grouped_files = defaultdict(list)
for file in files:
if ':' in file:
segment = file.split(':', 1)[1].strip()
else:
segment = file.strip()
comparison_key = segment[:compare_length]
# Add the file to a group with a shared comparison key
grouped_files[comparison_key].append(file]
folder_listbox.delete(0, tk.END)
sorted_grouped_keys = sorted(grouped_files) # Sort keys to display
for group_name in sorted_grouped_keys:
folder_listbox.insert(tk.END, group_name)
folder_listbox.grouped_files = grouped_files
Parameters:
compare_length: Number of characters from the segment to use for grouping (controlled by a slider).
Process:
List Files: Retrieves all files in the selected directory.
Extract Segment: For each file, splits the filename at the first colon (:) and trims any whitespace.
def show_folder_content(event):
widget = event.widget
if not widget.curselection():
return
index = widget.curselection()[0]
group_name = widget.get(index)
grouped_files = getattr(folder_listbox, 'grouped_files', {})
filenames_listbox.delete(0, tk.END)
for file in grouped_files.get(group_name, []):
filenames_listbox.insert(tk.END, file)
Functionality: When a user clicks on a group name in folder_listbox, this function displays all files in that group in filenames_listbox.
Example:
Clicking on the "finance_" group displays:
code
report: finance_Q1.xlsx
report: finance_Q2.xlsx
b. Renaming a Group
python
def rename_folder(event):
widget = event.widget
if not widget.curselection():
return
index = widget.curselection()[0]
old_name = widget.get(index)
new_name = simpledialog.askstring("Rename Folder", f"Enter new name for {old_name}:")
if new_name:
grouped_files = getattr(folder_listbox, 'grouped_files', {})
if old_name in grouped_files:
grouped_files[new_name] = grouped_files.pop(old_name)
widget.delete(index)
widget.insert(index, new_name)
Functionality: Allows the user to rename a group by double-clicking on it. Prompts for a new name and updates the group accordingly.
Example:
Double-clicking "finance_" prompts for a new name, say "Finance Reports".
The group updates to "Finance Reports" and contains the same files.
6. Applying Changes: Creating Folders and Moving Files
python
def apply_folders():
dir_path = dir_label.cget("text")
grouped_files = getattr(folder_listbox, 'grouped_files', {})
for folder_name, file_list in grouped_files.items():
folder_path = os.path.join(dir_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
for f in file_list:
src_file = os.path.join(dir_path, f)
dest_file = os.path.join(folder_path, f)
shutil.move(src_file, dest_file)
Functionality:
Iterates over each group.
Creates a corresponding folder if it doesn't already exist.
Moves each file in the group into the newly created folder.
Example:
After renaming, folders created:
"Finance Reports" containing:
report: finance_Q1.xlsx
report: finance_Q2.xlsx
"Marketing" containing:
report: marketing_Q1.xlsx
report: marketing_Q2.xlsx
"annual_" containing:
summary: annual_report.docx
The original directory structure is updated so that these files are now inside their respective folders.
Use the "Comparison Characters" slider to set how many characters from the segment after the colon are used for grouping. For this example, set it to 7.
Start Grouping:
Click the "Start Grouping" button.
The script processes the files and populates the Folder Listbox with groups based on the first 7 characters of each segment:
The original files are moved into their respective folders, neatly organizing the directory.
Additional Notes
Comparison Slider: Adjusting the slider changes how files are grouped. Increasing the number of comparison characters can create more specific groups, while decreasing it results in broader groupings.
Error Handling: The script includes basic checks, such as verifying if a directory is selected before attempting to group files.
Flexibility: The script can handle filenames with or without a colon (:). If a file doesn't contain a colon, the entire filename is considered for grouping based on the specified number of characters.
Customization: You can enhance the script further by adding features like previewing changes before applying them, handling naming conflicts, or supporting different grouping criteria.
Conclusion
Your script provides a user-friendly way to organize files within a directory by grouping them based on specific segments of their filenames. By leveraging the GUI built with Tkinter, users can interactively select directories, customize grouping parameters, view grouped files, rename groups, and apply changes to structure their files neatly. The step-by-step example above demonstrates how each part of the script contributes to this functionality.