To achieve the desired behavior—displaying all subfolders in the Folder Listbox when Folder Grouping is disabled and Group by File Number is enabled—you'll need to adjust how your application prepares and displays groups based on the selected options.
Here's a step-by-step guide to modifying your existing code to implement this functionality:
-
Extend the prepare_groups Function:
Modify the prepare_groups function to consider both Folder Grouping and Group by File Number settings. This will allow the function to create appropriate groups based on the user's selections.
-
Adjust Group Preparation Logic:
- When Folder Grouping is Enabled: Continue using the existing logic to group files based on cleaned filenames.
- When Folder Grouping is Disabled but Group by File Number is Enabled: Split all files into subgroups based on the specified number.
- When Both Are Disabled: Treat all files as a single group named "All Files."
-
Update the update_displayed_folders Function:
Ensure that the Folder Listbox reflects the newly prepared groups, whether they're based on filenames, file numbers, or treated as a single group.
-
Ensure Consistent Display and Sorting:
Make sure that all parts of the UI, including previews and sorting execution, align with the new grouping logic.
Below are the detailed modifications with code snippets:
1. Modify the prepare_groups Function
Update the prepare_groups function to handle the new logic:
def prepare_groups(files, grouping_enabled, group_by_number_enabled, file_num):
"""Prepare groups of files by cleaned filenames, by file number, or treat all as one group."""
if not files:
return {}
if grouping_enabled:
# Existing logic: Group by cleaned filenames
redundant_words = find_redundant_words(files)
temp_groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
temp_groups[cleaned_name].append(file)
# Sort files within each group based on numerical suffix
for group in temp_groups:
temp_groups[group].sort(key=extract_sort_key)
return temp_groups
elif group_by_number_enabled:
# New logic: Group by file number
try:
file_num = int(file_num)
if file_num <= 0:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for file grouping.")
return {}
subgroups = split_into_subgroups(files, file_num)
temp_groups = {}
for idx, subgroup in enumerate(subgroups, 1):
subgroup_name = f"Group {idx}"
temp_groups[subgroup_name] = subgroup
return temp_groups
else:
# Existing logic: Treat all files as a single group named "All Files"
return {"All Files": sorted(files)}
2. Update the load_directory Function
Ensure that the load_directory function passes the necessary parameters to prepare_groups:
def load_directory():
"""Load the selected directory, prepare groups, and update the displayed folders."""
global folder_path, groups, pending_renames, pending_merges, merge_history
folder_path = filedialog.askdirectory(title="Select the folder containing your files")
if not folder_path:
return
parent_folder_name = os.path.basename(folder_path)
parent_name_var.set(parent_folder_name)
try:
files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
groups = prepare_groups(files, grouping_enabled, group_by_number_enabled, file_num)
pending_renames.clear()
pending_merges.clear()
merge_history.clear()
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred while loading the directory:\n{str(e)}")
3. Modify the update_displayed_folders Function
Update update_displayed_folders to accommodate the new grouping logic:
def update_displayed_folders():
"""Update the folder_listbox based on current groups and selected options."""
global display_to_group_map
parent_prefix = parent_name_var.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
display_to_group_map.clear()
# Get the preview groups
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
preview_groups = prepare_groups(
[f for group in groups.values() for f in group],
grouping_enabled,
group_by_number_enabled,
file_num
)
# Update folder info
update_folder_info(preview_groups)
for folder_name in sorted(preview_groups.keys()):
display_name = folder_name
if grouping_enabled or (not grouping_enabled and group_by_number_enabled):
# When grouping is enabled or grouping is disabled but grouping by number is enabled
if capitalize_names:
modified_folder_name = capitalize_folder_name(display_name)
else:
modified_folder_name = display_name
if add_prefix:
modified_folder_name = f"{parent_prefix} - {modified_folder_name}"
else:
# When both grouping and grouping by number are disabled
modified_folder_name = parent_prefix
folder_listbox.insert(tk.END, modified_folder_name)
display_to_group_map[modified_folder_name] = folder_name
if folder_listbox.size() > 0:
folder_listbox.select_set(0)
show_folder_contents()
4. Adjust the execute_sorting Function
Ensure that the sorting execution aligns with the new grouping logic:
def execute_sorting():
"""Execute the sorting: move files into organized folders and subfolders based on selected options."""
if not folder_path or not groups:
messagebox.showerror("Error", "No directory loaded or no files grouped. Please load a directory first.")
return
try:
parent_prefix = parent_name_var.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
grouping_enabled = enable_grouping_var.get()
file_num_str = file_number_var.get().strip()
file_num = None
if group_files and file_num_str:
try:
file_num = int(file_num_str)
if file_num <= 0:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for file grouping.")
return
# Apply pending renames
for original_group, new_group in pending_renames.items():
if original_group in groups:
groups[new_group] = groups.pop(original_group)
pending_renames.clear()
pending_merges.clear()
merge_history.clear()
# Prepare groups based on current settings
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
groups = prepare_groups(
[f for group in groups.values() for f in group],
grouping_enabled,
group_by_number_enabled,
file_num
)
for folder_display_name, group_name in display_to_group_map.items():
files = groups.get(group_name, [])
if group_files and file_num and len(files) >= 2 * file_num:
subgroups = split_into_subgroups(files, file_num)
for idx, subgroup in enumerate(subgroups, 1):
subfolder_name = f"{parent_prefix} - {idx}"
subfolder_path = os.path.join(folder_path, subfolder_name)
os.makedirs(subfolder_path, exist_ok=True)
for file in subgroup:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
elif grouping_enabled and group_name != "All Files":
base_folder_name = capitalize_folder_name(group_name) if capitalize_names else group_name
modified_folder_name = f"{parent_prefix} - {base_folder_name}" if add_prefix else base_folder_name
new_folder_path = os.path.join(folder_path, modified_folder_name)
if os.path.abspath(new_folder_path) == os.path.abspath(folder_path):
messagebox.showerror("Error", f"Cannot create a folder with the same name as the parent folder: {modified_folder_name}")
continue
os.makedirs(new_folder_path, exist_ok=True)
for file in files:
src = os.path.join(folder_path, file)
dest = os.path.join(new_folder_path, file)
shutil.move(src, dest)
elif group_by_number_enabled:
# Handle grouping by number when folder grouping is disabled
if group_by_number_enabled and file_num:
subfolders = split_into_subgroups(files, file_num)
for idx, subgroup in enumerate(subfolders, 1):
subfolder_name = f"{parent_prefix} - {idx}"
subfolder_path = os.path.join(folder_path, subfolder_name)
os.makedirs(subfolder_path, exist_ok=True)
for file in subgroup:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
else:
subfolder_name = f"{parent_prefix}"
subfolder_path = os.path.join(folder_path, subfolder_name)
if os.path.abspath(subfolder_path) != os.path.abspath(folder_path):
os.makedirs(subfolder_path, exist_ok=True)
for file in files:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
messagebox.showinfo("Success", "Files sorted and organized successfully!")
reset_program()
except Exception as e:
messagebox.showerror("Error", f"An error occurred during sorting:\n{str(e)}")
5. Ensure UI Consistency
Ensure that the Group by File Number option interacts correctly with the Enable Folder Grouping option:
- When Folder Grouping is disabled and Group by File Number is enabled, the application should allow entering the number of files per subfolder and dynamically update the display.
6. Testing the Changes
After implementing the above changes, thoroughly test the application to ensure:
- Folder Grouping Enabled: Files are grouped based on cleaned filenames.
- Folder Grouping Disabled & Group by File Number Enabled: Files are split into subfolders based on the specified number.
- Both Options Disabled: All files are treated as a single group named "All Files."
- Edge Cases: Handle scenarios like invalid inputs, duplicate folder names, etc.
Complete Modified Code Snippets
Below I've included the modified parts of your original script with the necessary changes highlighted. This will help you integrate the changes seamlessly.
1. Updated prepare_groups Function
def prepare_groups(files, grouping_enabled, group_by_number_enabled, file_num):
"""Prepare groups of files by cleaned filenames, by file number, or treat all as one group."""
if not files:
return {}
if grouping_enabled:
# Identify redundant words/groups of characters
redundant_words = find_redundant_words(files)
temp_groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
temp_groups[cleaned_name].append(file)
# Sort files within each group based on numerical suffix
for group in temp_groups:
temp_groups[group].sort(key=extract_sort_key)
return temp_groups
elif group_by_number_enabled:
# Split all files into subgroups based on file_num
try:
file_num = int(file_num)
if file_num <= 0:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for file grouping.")
return {}
subgroups = split_into_subgroups(files, file_num)
temp_groups = {}
for idx, subgroup in enumerate(subgroups, 1):
subgroup_name = f"Group {idx}"
temp_groups[subgroup_name] = subgroup
return temp_groups
else:
# Treat all files as a single group named "All Files"
return {"All Files": sorted(files)}
2. Updated load_directory Function
def load_directory():
"""Load the selected directory, prepare groups, and update the displayed folders."""
global folder_path, groups, pending_renames, pending_merges, merge_history
folder_path = filedialog.askdirectory(title="Select the folder containing your files")
if not folder_path:
return
parent_folder_name = os.path.basename(folder_path)
parent_name_var.set(parent_folder_name)
try:
files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
groups = prepare_groups(files, grouping_enabled, group_by_number_enabled, file_num)
pending_renames.clear()
pending_merges.clear()
merge_history.clear()
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred while loading the directory:\n{str(e)}")
3. Updated update_displayed_folders Function
def update_displayed_folders():
"""Update the folder_listbox based on current groups and selected options."""
global display_to_group_map
parent_prefix = parent_name_var.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
display_to_group_map.clear()
# Get the preview groups
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
preview_groups = prepare_groups(
[f for group in groups.values() for f in group],
grouping_enabled,
group_by_number_enabled,
file_num
)
# Update folder info
update_folder_info(preview_groups)
for folder_name in sorted(preview_groups.keys()):
display_name = folder_name
if grouping_enabled or (not grouping_enabled and group_by_number_enabled):
# When grouping is enabled or grouping by number is enabled
if capitalize_names:
modified_folder_name = capitalize_folder_name(display_name)
else:
modified_folder_name = display_name
if add_prefix:
modified_folder_name = f"{parent_prefix} - {modified_folder_name}"
else:
# When both grouping and grouping by number are disabled
modified_folder_name = parent_prefix
folder_listbox.insert(tk.END, modified_folder_name)
display_to_group_map[modified_folder_name] = folder_name
if folder_listbox.size() > 0:
folder_listbox.select_set(0)
show_folder_contents()
4. Updated execute_sorting Function
def execute_sorting():
"""Execute the sorting: move files into organized folders and subfolders based on selected options."""
if not folder_path or not groups:
messagebox.showerror("Error", "No directory loaded or no files grouped. Please load a directory first.")
return
try:
parent_prefix = parent_name_var.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
grouping_enabled = enable_grouping_var.get()
file_num_str = file_number_var.get().strip()
file_num = None
if group_files and file_num_str:
try:
file_num = int(file_num_str)
if file_num <= 0:
raise ValueError
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for file grouping.")
return
# Apply pending renames
for original_group, new_group in pending_renames.items():
if original_group in groups:
groups[new_group] = groups.pop(original_group)
pending_renames.clear()
pending_merges.clear()
merge_history.clear()
# Prepare groups based on current settings
grouping_enabled = enable_grouping_var.get()
group_by_number_enabled = group_files_var.get()
file_num = file_number_var.get().strip()
groups = prepare_groups(
[f for group in groups.values() for f in group],
grouping_enabled,
group_by_number_enabled,
file_num
)
for folder_display_name, group_name in display_to_group_map.items():
files = groups.get(group_name, [])
if group_files and file_num and len(files) >= 2 * file_num:
subgroups = split_into_subgroups(files, file_num)
for idx, subgroup in enumerate(subgroups, 1):
subfolder_name = f"{parent_prefix} - {idx}"
subfolder_path = os.path.join(folder_path, subfolder_name)
os.makedirs(subfolder_path, exist_ok=True)
for file in subgroup:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
elif grouping_enabled and group_name != "All Files":
base_folder_name = capitalize_folder_name(group_name) if capitalize_names else group_name
modified_folder_name = f"{parent_prefix} - {base_folder_name}" if add_prefix else base_folder_name
new_folder_path = os.path.join(folder_path, modified_folder_name)
if os.path.abspath(new_folder_path) == os.path.abspath(folder_path):
messagebox.showerror("Error", f"Cannot create a folder with the same name as the parent folder: {modified_folder_name}")
continue
os.makedirs(new_folder_path, exist_ok=True)
for file in files:
src = os.path.join(folder_path, file)
dest = os.path.join(new_folder_path, file)
shutil.move(src, dest)
elif group_by_number_enabled:
# Handle grouping by number when folder grouping is disabled
if group_by_number_enabled and file_num:
subfolders = split_into_subgroups(files, file_num)
for idx, subgroup in enumerate(subfolders, 1):
subfolder_name = f"{parent_prefix} - {idx}"
subfolder_path = os.path.join(folder_path, subfolder_name)
os.makedirs(subfolder_path, exist_ok=True)
for file in subgroup:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
else:
subfolder_name = f"{parent_prefix}"
subfolder_path = os.path.join(folder_path, subfolder_name)
if os.path.abspath(subfolder_path) != os.path.abspath(folder_path):
os.makedirs(subfolder_path, exist_ok=True)
for file in files:
src = os.path.join(folder_path, file)
dest = os.path.join(subfolder_path, file)
shutil.move(src, dest)
messagebox.showinfo("Success", "Files sorted and organized successfully!")
reset_program()
except Exception as e:
messagebox.showerror("Error", f"An error occurred during sorting:\n{str(e)}")
7. Additional Considerations
-
Naming Subfolders: The current implementation names subfolders as "Group 1", "Group 2", etc., when grouping by file number. You can customize this naming convention as per your preference.
-
UI Enhancements: You might want to disable the Add Parent Name Prefix option when grouping by file number to avoid overly long folder names, depending on your requirements.
-
Validation: Ensure that all user inputs are validated to prevent errors during execution, especially when dealing with file operations.
-
Logging: For better debugging and user feedback, consider adding logging to track the application's operations.
By implementing these modifications, your application will now correctly display all subfolders in the Folder Listbox when Folder Grouping is disabled and Group by File Number is enabled. This enhances the flexibility of your file sorting tool, allowing users to organize their files precisely as they need.
Feel free to reach out if you encounter any issues or need further assistance with specific parts of the implementation!