import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
# 1. Ignore text before and including ':'.
filename = filename.split(':', 1)[-1]
code
# 2. Remove file extension.
filename = os.path.splitext(filename)[0]
# 3. Replace delimiters with spaces, and transform to lowercase.
words = filename.replace('_', ' ').lower().split()
# 4. Remove redundant words/groups of characters.
unique_words = [w for w in words if w not in redundant_words]
# 5. Remove words that are numeric or less than 3 characters, and remove duplicates
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not any(c.isdigit() for c in word) and not (word in seen or seen.add(word))]
# Join cleaned words back into a string
cleaned_filename = ' '.join(cleaned_words)
# Use a placeholder for files that end up without significant content
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
"""Identify groups of characters that appear in all filenames."""
if not files:
return []
code
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
"""Prepare groups of files by cleaned filenames."""
if not files:
return {}
code
# Identify redundant words/groups of characters
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event):
"""Display files in the selected folder."""
selection = folder_listbox.curselection()
if not selection:
return
code
folder_name = folder_listbox.get(selection[0])
files = groups.get(folder_name, [])
content_listbox.delete(0, tk.END)
for file in files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
folder_path = filedialog.askdirectory(title="Select the folder containing your files")
if not folder_path:
return
code
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
folder_listbox.insert(tk.END, folder_name)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def execute_sorting():
if not folder_path or not groups:
messagebox.showerror("Error", "No directory loaded or no files grouped. Please load a directory first.")
return
code
try:
for folder_name, files in groups.items():
new_folder_path = os.path.join(folder_path, folder_name)
os.makedirs(new_folder_path, exist_ok=True)
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
messagebox.showinfo("Success", "Files sorted successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
root.mainloop()
What is the procedure order for cleaning the file name?
Assistant
The procedure for cleaning the file name in the provided script is as follows:
Ignore text before and including ':': The filename is split at the first occurrence of the colon character (or the full-width equivalent ':'), and only the substring after this character is kept.
Remove file extension: The file extension, typically following a dot (e.g., .txt, .jpg), is removed.
Normalize delimiters and transform to lowercase: Any underscores in the filename are replaced with spaces, and the entire string is converted to lowercase.
Remove redundant words/groups of characters: The cleaned filename is split into words. Any words found in the list of redundant words (which are identified as words common to all filenames in the directory) are removed.
Remove words that are numeric or less than 3 characters and ensure uniqueness: The remaining words are filtered to exclude those containing numbers or those shorter than three characters. Duplicates are also removed by maintaining a set of seen words.
Join cleaned words back into a string: The remaining cleaned and filtered words are joined into a single string separated by spaces.
Use a placeholder for insignificant content: If this cleaning process results in an empty string, a default placeholder name "misc_files" is used instead.
User
Are the steps performed in this order?
Assistant
Yes, the steps in the clean_filename function are performed in the order described. Here is the detailed progression as seen in the function:
Ignore text before and including ':': This is done with the line filename = filename.split(':', 1)[-1]. It splits the filename at the first occurrence of ':' and keeps the part after it.
Remove file extension: This step is done immediately after by using filename = os.path.splitext(filename)[0], which removes the file extension.
Normalize delimiters and transform to lowercase: The line words = filename.replace('_', ' ').lower().split() replaces underscores with spaces, converts the string to lowercase, and splits it into a list of words.
Remove redundant words/groups of characters: The list comprehension unique_words = [w for w in words if w not in redundant_words] filters out any words identified as redundant.
Remove words that are numeric or less than 3 characters and remove duplicates: This is handled by the next list comprehension cleaned_words = [word for word in unique_words if len(word) > 2 and not any(c.isdigit() for c in word) and not (word in seen or seen.add(word))]. It ensures words are at least three characters long, do not contain digits, and are unique.
Join cleaned words back into a string: The cleaned words are joined with cleaned_filename = ' '.join(cleaned_words).
Use a placeholder for insignificant content: Finally, the function returns cleaned_filename or "misc_files" if cleaned_filename is empty: return cleaned_filename if cleaned_filename else "misc_files".
These steps ensure that the filename is systematically processed to retain only meaningful components following the specified rules.
User
I don't understand why 0506:Ifrete_Decorated100855984decorated_5.jpg goes to the misc_files folder.
Assistant
Let's break down what happens during the execution of the clean_filename function for the filename 0506:Ifrete_Decorated100855984decorated_5.jpg to see why it might end up as misc_files:
Ignore text before and including ':':
The function splits the filename based on the colon (:) and keeps the portion after it.
Result: Ifrete_Decorated100855984decorated_5.jpg
Remove file extension:
The function removes the file extension, which is .jpg in this case.
Result: Ifrete_Decorated100855984decorated_5
Normalize delimiters and transform to lowercase:
The underscores (_) are replaced with spaces, and the string is converted to lowercase.
Result: ifrete decorated100855984decorated 5
Remove redundant words/groups of characters:
Assuming no common redundant words were identified in other filenames, this step might not remove any words.
Result: ifrete decorated100855984decorated 5
Remove words that are numeric or less than 3 characters and remove duplicates:
The function filters out the words that contain numbers (decorated100855984decorated and 5) and words that are less than 3 characters long (none in this case).
What's left after filtering might be nothing in this case, or possibly just parts with numbers that were stripped out when integrated with word uniqueness.
Result: [] or a list representing empty or fully unique stripped due to number content.
Join cleaned words back into a string:
Join the filtered words, which likely results in an empty string since all words might have been filtered out.
Result: ""
Use a placeholder for insignificant content:
Since the result is an empty string, the function returns "misc_files".
This process illustrates how words containing digits and short words are stripped out, which can sometimes result in an empty string, defaulting to "misc_files". If you don't want this behavior for specific cases like retaining certain words even with digits integrated or adjusting rules on filtered words, you might need to modify the filtering logic to include more conditions or adjust the criteria used for filtering out words.
User
Perhaps we should replace all number group to space. However, do not perform this action if the filename is compose of only numbers.
Assistant
To modify the behavior to replace all numeric groups with spaces, while ensuring that filenames composed entirely of numbers remain unchanged, you can adjust the clean_filename function accordingly. Here’s how you can implement these changes:
Check if the filename is only composed of numbers before removing them.
Replace numeric groups with spaces in filenames that are not solely numeric.
Here's how you can update the clean_filename function to incorporate this logic:
python
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
# 1. Ignore text before and including ':'.
filename = filename.split(':', 1)[-1]
# 2. Remove file extension.
filename = os.path.splitext(filename)[0]
# 3. Replace delimiters with spaces, and transform to lowercase.
words = filename.replace('_', ' ').lower().split()
# Check if the entire filename is numeric
if all(part.isdigit() for part in words):
# If yes, return it as a single string joined by spaces (i.e., do not modify)
return ' '.join(words)
# 4. Replace numeric groups with spaces
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
# 5. Remove redundant words/groups of characters.
unique_words = [w for w in words if w not in redundant_words]
# 6. Remove words that are less than 3 characters and ensure uniqueness
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
# Join cleaned words back into a string
cleaned_filename = ' '.join(cleaned_words)
# Use a placeholder for files that end up without significant content
return cleaned_filename if cleaned_filename else "misc_files"
Key Modifications:
Numeric-only Filenames: Before modifying the numeric content, the function checks if the filename is composed entirely of numeric parts. If true, it preserves the filename simply by joining the numeric parts with spaces.
Replacement of Numeric Groups: For non-numeric-only filenames, numeric groups are replaced with spaces using a regular expression re.sub(r'\d+', ' ', word).strip().
This approach ensures that filenames composed entirely of numbers remain unchanged, while files with mixed alphanumeric content have their numeric components replaced with spaces, reducing redundancy while maintaining meaningful words.
User
How come this file doesn't have the duplicated word removed?
0117:Ifrete_Kunoichi100664721kunoichi_6.jpg
Assistant
The issue of duplicated words not being removed in the file 0117:Ifrete_Kunoichi100664721kunoichi_6.jpg comes down to how the process handles words and their filtering. Let's look at why this happens with the current logic and how to address it.
Here's a breakdown of how the function processes this filename:
Ignore text before and including ':':
Result: Ifrete_Kunoichi100664721kunoichi_6.jpg
Remove file extension:
Result: Ifrete_Kunoichi100664721kunoichi_6
Normalize delimiters and transform to lowercase:
Result: ifrete kunoichi100664721kunoichi 6
Replace numeric groups with spaces:
Using re.sub(r'\d+', ' ', word).strip(), non-numeric parts are retained, but numbers are removed.
Result: ifrete kunoichi kunoichi
Remove redundant words/groups of characters:
This function step will typically remove common words across multiple similar filenames.
In this filename, there might not be enough sample variety to identify 'kunoichi' as redundant without removing different contexts within sample sets.
Remove words that are less than 3 characters and ensure uniqueness:
The current design keeps unique words but does not handle the same word repeated within a single filename.
Proposed Solution
To address the issue with duplicated words within a single file not being removed after numeric stripping, adjust the filtering/cleanup process to explicitly check for and remove duplicates directly. Here's how you can update the clean_filename function:
python
User
This works very well.
Now I think the Sort and Preview Names button is redundant. The Browse Directory already cover most of its functions.
Can you rename the labelling of the Execute Sorting Button to Execute and place it to the button right hand corner?
Now I need to add some options to the program.
Display the parent folder name in a entry box so that it can be modified.
checkbox option for adding parent folder name (from the entry box in 1)) to the prefix of the folder name (add a hyphen with spaces ( - ).
checkbox option for grouping folder content into subfolders according to a file number (FileNum) specified by user. Please note that while moving files into subfolder if the remaining files is less than twice the value of FileNum, all the remaining files will be placed into one subfolder. The subfolder names will be the serialized folder name (number at the end).
checkbox option for capitalzied the first letter of every word in the folder (except of the words of, is, a etc.)
From the Folder Listbox, I can rename the folder name on the spot (using context menu) and merge folders by selecting two or more folders (using context menu)
Assistant
To implement these changes, you’ll need to modify several parts of the program, including the GUI layout, logic for file sorting, and how folder names are processed and modified.
Here's how you can go about implementing the requested changes:
GUI Modifications
Rename the "Execute Sorting" Button to "Execute" and move it:
Update the button text and reposition it using grid or pack layout options for bottom-right positioning.
Add Entry Box for Parent Folder Name and Checkboxes:
Add an entry widget for modifying the parent folder name.
Add checkboxes for the specified options.
Logic Modifications
Modify the renaming and moving logic to handle new features:
Use the entry box value for adding prefixes.
Handle checkbox states to execute additional tasks like prefixing, subfolder grouping, and capitalization.
Add context menu functionalities to listbox for renaming and merging.
Here's an outline of how you might implement some of these features in the code:
python
User
When a directory is loaded, it should have the parent folder number displayed in the Entry Box.
The program should show the result immediately after an option is selected.
Assistant
To provide immediate feedback in the application after an option is selected, we'll need to trigger the file grouping and display updates upon changes to the options (checkboxes and entry boxes). We will also modify the entry box to display the parent folder's name immediately after a directory is loaded.
Here's how you can achieve these requirements:
Display the parent directory name in the entry box when a directory is loaded.
Update the folder grouping and listbox display immediately when options are updated.
Let's update the code accordingly:
python
User
Once the selected options are updated, the user can no longer see the content of the folder.
Moreover, whne the Group by number option is selected, I do not see the subfolders.
Assistant
Let's revise the approach to ensure that folder content is visible and subfolders are correctly displayed when options are selected or updated. Specifically, we'll need to update the show_folder_contents function to reflect changes made by options, and ensure subfolders are displayed when the "Group by file number" option is selected.
Key Improvements
Display folder contents correctly:
After options are applied, make sure the selected folder's contents are still displayed.
Show subfolder contents when "Group by file number" is selected:
When grouping files into subfolders, ensure the list of subfolders is visible in the user interface.
Here's an improved approach to handling these functionalities:
python
User
I am no longer seeing the filenames from the filename Listbox.
Assistant
The issue with filenames not appearing in the content listbox after applying options likely stems from the way the content is being updated based on the folder listbox selection. Let's revise the code to better handle the display of file content while taking user preferences into account.
Here's a step-by-step approach to ensure file contents are always displayed correctly:
Ensure the show_folder_contents function directly pulls file content from the directory.
Update the content when listbox selections change, adhering to the current options.
Here's how you can modify the code to address these concerns:
python
User
I don't see the content of the folder shows in the Listbox
Assistant
Let's ensure that the content of the selected folder is displayed in the content listbox correctly. I'll revise the approach to manually fetch and display the files within the folder, including when subfolders are created.
Here's how we can ensure that the content of the selected folder or subfolder is properly retrieved and displayed:
Fetch and display file contents directly from the directory.
Ensure we're listing files or subfolder contents accurately based on whether grouping is applied.
Let's update the code again to focus on displaying this information correctly:
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
# 1. Ignore text before and including ':'.
filename = filename.split(':', 1)[-1]
# 2. Remove file extension.
filename = os.path.splitext(filename)[0]
# 3. Replace delimiters with spaces, and transform to lowercase.
words = filename.replace('_', ' ').lower().split()
# Check if the entire filename is numeric
if all(part.isdigit() for part in words):
return ' '.join(words)
# 4. Replace numeric groups with spaces
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
# Flatten the words split further on spaces
words = ' '.join(words).split()
# 5. Remove redundant words/groups of characters.
unique_words = [w for w in words if w not in redundant_words]
# 6. Remove words that are less than 3 characters and ensure uniqueness across filename
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
# Join cleaned words back into a string
cleaned_filename = ' '.join(cleaned_words)
# Use a placeholder for files that end up without significant content
return cleaned_filename if cleaned_filename else "misc_files"
Explanation
Unifying Words After Numeric Cleaning: Reconstruct and split words again after stripping to ensure words are correctly separated before deduplication.
Ensure Uniqueness Across Files: The uniqueness logic applies globally after redundant and numeric filtering is complete, ensuring duplicates like 'kunoichi' are removed.
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
# 1. Ignore text before and including ':'.
filename = filename.split(':', 1)[-1]
# 2. Remove file extension.
filename = os.path.splitext(filename)[0]
# 3. Replace delimiters with spaces, and transform to lowercase.
words = filename.replace('_', ' ').lower().split()
# Check if the entire filename is numeric
if all(part.isdigit() for part in words):
return ' '.join(words)
# 4. Replace numeric groups with spaces
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
# Flatten the words split further on spaces
words = ' '.join(words).split()
# 5. Remove redundant words/groups of characters.
unique_words = [w for w in words if w not in redundant_words]
# 6. Remove words that are less than 3 characters and ensure uniqueness across filename
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
# Join cleaned words back into a string
cleaned_filename = ' '.join(cleaned_words)
# Use a placeholder for files that end up without significant content
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
"""Identify groups of characters that appear in all filenames."""
if not files:
return []
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
"""Prepare groups of files by cleaned filenames."""
if not files:
return {}
# Identify redundant words/groups of characters
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event):
"""Display files in the selected folder."""
selection = folder_listbox.curselection()
if not selection:
return
folder_name = folder_listbox.get(selection[0])
files = groups.get(folder_name, [])
content_listbox.delete(0, tk.END)
for file in files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
folder_path = filedialog.askdirectory(title="Select the folder containing your files")
if not folder_path:
return
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
folder_listbox.insert(tk.END, folder_name)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def execute_sorting():
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_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
for folder_name, files in groups.items():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
new_folder_path = os.path.join(folder_path, folder_name)
os.makedirs(new_folder_path, exist_ok=True)
# Implement grouping into subfolders if needed
if group_files and file_number:
index = 0
for idx, file in enumerate(files):
subfolder_index = idx // file_number
if idx + file_number >= len(files):
subfolder_index = 0 # Group remaining files
subfolder_path = os.path.join(new_folder_path, str(subfolder_index + 1))
os.makedirs(subfolder_path, exist_ok=True)
shutil.move(os.path.join(folder_path, file), os.path.join(subfolder_path, file))
else:
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
# Capitalize folder names
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
new_folder_path = os.path.join(folder_path, folder_name)
# Update folder names in listbox
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
folder_listbox.insert(tk.END, folder_name)
messagebox.showinfo("Success", "Files sorted and organized successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
# Create a simple GUI
root = tk.Tk()
root.title("File Sorter")
frame = tk.Frame(root)
frame.pack(pady=20, padx=20)
parent_name_label = tk.Label(frame, text="Parent Folder Name:")
parent_name_label.grid(row=0, column=0, padx=10)
parent_name_entry = tk.Entry(frame, width=30)
parent_name_entry.grid(row=0, column=1, padx=10)
prefix_var = tk.IntVar()
prefix_check = tk.Checkbutton(frame, text="Add Parent Name Prefix", variable=prefix_var)
prefix_check.grid(row=1, column=0, columnspan=2, pady=5)
group_files_var = tk.IntVar()
group_files_check = tk.Checkbutton(frame, text="Group by file number:", variable=group_files_var)
group_files_check.grid(row=2, column=0)
file_number_entry = tk.Entry(frame, width=5)
file_number_entry.grid(row=2, column=1, sticky='w')
capitalize_var = tk.IntVar()
capitalize_check = tk.Checkbutton(frame, text="Capitalize Folder Names", variable=capitalize_var)
capitalize_check.grid(row=3, column=0, columnspan=2, pady=5)
folder_listbox = tk.Listbox(frame, width=40, height=15)
folder_listbox.grid(row=4, column=0, columnspan=2, pady=5)
content_listbox = tk.Listbox(frame, width=40, height=15)
content_listbox.grid(row=4, column=2, columnspan=2, pady=5)
folder_listbox.bind("<<ListboxSelect>>", show_folder_contents)
browse_button = tk.Button(frame, text="Browse Directory", command=load_directory)
browse_button.grid(row=5, column=0, pady=10, sticky='w')
execute_button = tk.Button(frame, text="Execute", command=execute_sorting)
execute_button.grid(row=5, column=3, pady=10, sticky='e')
root.mainloop()
Explanation:
Entry and Checkbox for Parent Folder Name:
An entry box is added where users can input the parent folder name. A corresponding checkbox enables adding this as a prefix to new folders.
File Number Input and Checkboxes:
A checkbox and entry allow users to opt for grouping files into subfolders based on a specified number. The code respects this option and adjusts subfolder logic during execution.
Capitalization Option:
This checkbox enables user choice in capitalizing new folder names.
Context Menu Enhancements:
While not fully implemented in this snippet, adding a context menu for renaming folders in the listbox would require further extensions using a Menu widget bound to right-click events.
This plan provides a structured UI and logical flow to handle all specified features, simplifying tasks and enhancing flexibility for users. Further refinements may be required to handle edge cases, such as error handling and input validation.
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
filename = filename.split(':', 1)[-1]
filename = os.path.splitext(filename)[0]
words = filename.replace('_', ' ').lower().split()
if all(part.isdigit() for part in words):
return ' '.join(words)
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
words = ' '.join(words).split()
unique_words = [w for w in words if w not in redundant_words]
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
cleaned_filename = ' '.join(cleaned_words)
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
if not files:
return []
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
if not files:
return {}
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event):
selection = folder_listbox.curselection()
if not selection:
return
folder_name = folder_listbox.get(selection[0])
files = groups.get(folder_name, [])
content_listbox.delete(0, tk.END)
for file in files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
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_entry.delete(0, tk.END)
parent_name_entry.insert(0, parent_folder_name)
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def apply_options():
update_displayed_folders()
show_folder_contents(None)
def update_displayed_folders():
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
folder_listbox.insert(tk.END, folder_name)
def execute_sorting():
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_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
for folder_name, files in groups.items():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
new_folder_path = os.path.join(folder_path, folder_name)
os.makedirs(new_folder_path, exist_ok=True)
if group_files and file_number:
index = 0
for idx, file in enumerate(files):
subfolder_index = idx // file_number
if idx + file_number >= len(files):
subfolder_index = 0
subfolder_path = os.path.join(new_folder_path, str(subfolder_index + 1))
os.makedirs(subfolder_path, exist_ok=True)
shutil.move(os.path.join(folder_path, file), os.path.join(subfolder_path, file))
else:
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
messagebox.showinfo("Success", "Files sorted and organized successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
root = tk.Tk()
root.title("File Sorter")
frame = tk.Frame(root)
frame.pack(pady=20, padx=20)
parent_name_label = tk.Label(frame, text="Parent Folder Name:")
parent_name_label.grid(row=0, column=0, padx=10)
parent_name_entry = tk.Entry(frame, width=30)
parent_name_entry.grid(row=0, column=1, padx=10)
prefix_var = tk.IntVar()
prefix_check = tk.Checkbutton(frame, text="Add Parent Name Prefix", variable=prefix_var, command=apply_options)
prefix_check.grid(row=1, column=0, columnspan=2, pady=5)
group_files_var = tk.IntVar()
group_files_check = tk.Checkbutton(frame, text="Group by file number:", variable=group_files_var, command=apply_options)
group_files_check.grid(row=2, column=0)
file_number_entry = tk.Entry(frame, width=5)
file_number_entry.grid(row=2, column=1, sticky='w')
capitalize_var = tk.IntVar()
capitalize_check = tk.Checkbutton(frame, text="Capitalize Folder Names", variable=capitalize_var, command=apply_options)
capitalize_check.grid(row=3, column=0, columnspan=2, pady=5)
folder_listbox = tk.Listbox(frame, width=40, height=15)
folder_listbox.grid(row=4, column=0, columnspan=2, pady=5)
content_listbox = tk.Listbox(frame, width=40, height=15)
content_listbox.grid(row=4, column=2, columnspan=2, pady=5)
folder_listbox.bind("<<ListboxSelect>>", show_folder_contents)
browse_button = tk.Button(frame, text="Browse Directory", command=load_directory)
browse_button.grid(row=5, column=0, pady=10, sticky='w')
execute_button = tk.Button(frame, text="Execute", command=execute_sorting)
execute_button.grid(row=5, column=3, pady=10, sticky='e')
root.mainloop()
Explanation:
Parent Folder Name Display:
When a directory is selected, its name is extracted and populated in the parent_name_entry to allow user modification.
Dynamic Option Application:
Each checkbox update calls apply_options(), which updates the folder display based on current selections. It refreshes the folder list in folder_listbox.
Real-Time Feedback:
The folder names reflect selections like prefix addition and name capitalization immediately due to the automatic update once selections change or the entry box is altered.
These modifications provide the functionality to preview and modify folder names and structures based on the options selected before executing the final sorting operation.
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
filename = filename.split(':', 1)[-1]
filename = os.path.splitext(filename)[0]
words = filename.replace('_', ' ').lower().split()
if all(part.isdigit() for part in words):
return ' '.join(words)
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
words = ' '.join(words).split()
unique_words = [w for w in words if w not in redundant_words]
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
cleaned_filename = ' '.join(cleaned_words)
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
if not files:
return []
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
if not files:
return {}
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event):
"""Display files in the selected folder or its subfolders based on state."""
selection = folder_listbox.curselection()
if not selection:
return
folder_name = folder_listbox.get(selection[0])
selected_files = groups.get(folder_name, [])
# Check inside subfolders if grouping is enabled
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
content_listbox.delete(0, tk.END)
possible_path = os.path.join(folder_path, folder_name)
if add_prefix:
prefixed_name = f"{parent_prefix} - {folder_name}"
else:
prefixed_name = folder_name
if capitalize_names:
prefixed_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in prefixed_name.split()])
if os.path.exists(possible_path):
subfolders = [f for f in os.listdir(possible_path) if os.path.isdir(os.path.join(possible_path, f))]
if group_files and subfolders:
content_listbox.insert(tk.END, "Subfolders:")
for subfolder in subfolders:
content_listbox.insert(tk.END, f" {subfolder}")
else:
for file in selected_files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
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_entry.delete(0, tk.END)
parent_name_entry.insert(0, parent_folder_name)
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def apply_options():
update_displayed_folders()
show_folder_contents(None)
def update_displayed_folders():
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
folder_listbox.insert(tk.END, folder_name)
def execute_sorting():
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_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
for folder_name, files in groups.items():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
new_folder_path = os.path.join(folder_path, folder_name)
os.makedirs(new_folder_path, exist_ok=True)
if group_files and file_number:
index = 0
for idx, file in enumerate(files):
subfolder_index = idx // file_number
if idx + file_number >= len(files) and subfolder_index > 0:
subfolder_index = 0
subfolder_path = os.path.join(new_folder_path, str(subfolder_index + 1))
os.makedirs(subfolder_path, exist_ok=True)
shutil.move(os.path.join(folder_path, file), os.path.join(subfolder_path, file))
else:
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
messagebox.showinfo("Success", "Files sorted and organized successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
root = tk.Tk()
root.title("File Sorter")
frame = tk.Frame(root)
frame.pack(pady=20, padx=20)
parent_name_label = tk.Label(frame, text="Parent Folder Name:")
parent_name_label.grid(row=0, column=0, padx=10)
parent_name_entry = tk.Entry(frame, width=30)
parent_name_entry.grid(row=0, column=1, padx=10)
prefix_var = tk.IntVar()
prefix_check = tk.Checkbutton(frame, text="Add Parent Name Prefix", variable=prefix_var, command=apply_options)
prefix_check.grid(row=1, column=0, columnspan=2, pady=5)
group_files_var = tk.IntVar()
group_files_check = tk.Checkbutton(frame, text="Group by file number:", variable=group_files_var, command=apply_options)
group_files_check.grid(row=2, column=0)
file_number_entry = tk.Entry(frame, width=5)
file_number_entry.grid(row=2, column=1, sticky='w')
capitalize_var = tk.IntVar()
capitalize_check = tk.Checkbutton(frame, text="Capitalize Folder Names", variable=capitalize_var, command=apply_options)
capitalize_check.grid(row=3, column=0, columnspan=2, pady=5)
folder_listbox = tk.Listbox(frame, width=40, height=15)
folder_listbox.grid(row=4, column=0, columnspan=2, pady=5)
content_listbox = tk.Listbox(frame, width=40, height=15)
content_listbox.grid(row=4, column=2, columnspan=2, pady=5)
folder_listbox.bind("<<ListboxSelect>>", show_folder_contents)
browse_button = tk.Button(frame, text="Browse Directory", command=load_directory)
browse_button.grid(row=5, column=0, pady=10, sticky='w')
execute_button = tk.Button(frame, text="Execute", command=execute_sorting)
execute_button.grid(row=5, column=3, pady=10, sticky='e')
root.mainloop()
Key Changes:
Subfolder Display in the show_folder_contents function:
A check for grouping option enables listing subfolder names when they exist under the selected folder. This helps users see the new structure post-option selection.
Immediate Visibility of Folder Changes:
Updated file content display when you toggle options like adding prefixes or capitalizing names, ensuring the changes are directly visible.
Explanation:
Subfolder Listing: If subfolder grouping is enabled, the script checks if subfolders were created and lists them.
Dynamic Updates: The apply_options function makes sure every change in preferences is reflected by updating the listbox, ensuring the user sees immediate alterations.
This setup enhances the program's usability by keeping folder content visible even when options are active and showing grouped subfolders appropriately.
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
filename = filename.split(':', 1)[-1]
filename = os.path.splitext(filename)[0]
words = filename.replace('_', ' ').lower().split()
if all(part.isdigit() for part in words):
return ' '.join(words)
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
words = ' '.join(words).split()
unique_words = [w for w in words if w not in redundant_words]
seen = set()
cleaned_words = [word for word in unique_words if len(word) > 2 and not (word in seen or seen.add(word))]
cleaned_filename = ' '.join(cleaned_words)
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
if not files:
return []
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
if not files:
return {}
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event=None):
"""Display files in the selected folder or its subfolders based on state."""
selection = folder_listbox.curselection()
if not selection:
return
folder_name = folder_listbox.get(selection[0])
selected_files = groups.get(folder_name, [])
# Display files or subfolder contents based on configuration
content_listbox.delete(0, tk.END)
# Directly list files in current directory structure
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
modified_folder_name = folder_name
if add_prefix:
modified_folder_name = f"{parent_prefix} - {modified_folder_name}"
if capitalize_names:
modified_folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in modified_folder_name.split()])
# Check actual folder path with modifications
possible_path = os.path.join(folder_path, modified_folder_name)
if os.path.exists(possible_path):
if group_files:
# Check and list subfolders if they exist
subfolders = [f for f in os.listdir(possible_path) if os.path.isdir(os.path.join(possible_path, f))]
if subfolders: # If subfolders exist, show them
content_listbox.insert(tk.END, "Subfolders:")
for subfolder in subfolders:
subfolder_path = os.path.join(possible_path, subfolder)
content_listbox.insert(tk.END, f" {subfolder}/")
subfolder_files = os.listdir(subfolder_path)
for file in subfolder_files:
content_listbox.insert(tk.END, f" {file}")
else:
content_listbox.insert(tk.END, "Files:")
for file in selected_files:
content_listbox.insert(tk.END, file)
else:
# Simply list files without grouping
content_listbox.insert(tk.END, "Files:")
for file in selected_files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
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_entry.delete(0, tk.END)
parent_name_entry.insert(0, parent_folder_name)
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def apply_options():
update_displayed_folders()
show_folder_contents()
def update_displayed_folders():
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in folder_name.split()])
folder_listbox.insert(tk.END, folder_name)
def execute_sorting():
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_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
for folder_name, files in groups.items():
modified_folder_name = folder_name
if add_prefix:
modified_folder_name = f"{parent_prefix} - {modified_folder_name}"
if capitalize_names:
modified_folder_name = ' '.join([word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word for word in modified_folder_name.split()])
new_folder_path = os.path.join(folder_path, modified_folder_name)
os.makedirs(new_folder_path, exist_ok=True)
if group_files and file_number:
# Create and manage subfolders
index = 0
for idx, file in enumerate(files):
subfolder_index = idx // file_number
if idx + file_number >= len(files) and subfolder_index > 0:
subfolder_index = 0
subfolder_path = os.path.join(new_folder_path, str(subfolder_index + 1))
os.makedirs(subfolder_path, exist_ok=True)
shutil.move(os.path.join(folder_path, file), os.path.join(subfolder_path, file))
else:
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
messagebox.showinfo("Success", "Files sorted and organized successfully!")
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
root = tk.Tk()
root.title("File Sorter")
frame = tk.Frame(root)
frame.pack(pady=20, padx=20)
parent_name_label = tk.Label(frame, text="Parent Folder Name:")
parent_name_label.grid(row=0, column=0, padx=10)
parent_name_entry = tk.Entry(frame, width=30)
parent_name_entry.grid(row=0, column=1, padx=10)
prefix_var = tk.IntVar()
prefix_check = tk.Checkbutton(frame, text="Add Parent Name Prefix", variable=prefix_var, command=apply_options)
prefix_check.grid(row=1, column=0, columnspan=2, pady=5)
group_files_var = tk.IntVar()
group_files_check = tk.Checkbutton(frame, text="Group by file number:", variable=group_files_var, command=apply_options)
group_files_check.grid(row=2, column=0)
file_number_entry = tk.Entry(frame, width=5)
file_number_entry.insert(0, "5") # Default for file grouping
file_number_entry.grid(row=2, column=1, sticky='w')
capitalize_var = tk.IntVar()
capitalize_check = tk.Checkbutton(frame, text="Capitalize Folder Names", variable=capitalize_var, command=apply_options)
capitalize_check.grid(row=3, column=0, columnspan=2, pady=5)
folder_listbox = tk.Listbox(frame, width=40, height=15)
folder_listbox.grid(row=4, column=0, columnspan=2, pady=5)
content_listbox = tk.Listbox(frame, width=40, height=15)
content_listbox.grid(row=4, column=2, columnspan=2, pady=5)
folder_listbox.bind("<<ListboxSelect>>", show_folder_contents)
browse_button = tk.Button(frame, text="Browse Directory", command=load_directory)
browse_button.grid(row=5, column=0, pady=10, sticky='w')
execute_button = tk.Button(frame, text="Execute", command=execute_sorting)
execute_button.grid(row=5, column=3, pady=10, sticky='e')
root.mainloop()
Explanation:
Dynamic Display of Content:
The show_folder_contents function now checks if subfolders exist and displays them appropriately when options are selected. If not, it defaults to showing files.
Immediate Option Effects:
Ensures that toggling options updates both the folder names and their displayed contents promptly, maintaining user clarity.
Controller Logic:
Logic behind folder naming and subfolder listing adapts to current checkbox statuses, aligning with real-time changes made by users.
This solution should ensure both the contents and folder structures are visible immediately after changes, fostering a more interactive and transparent experience for users.
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
import re
from collections import defaultdict
def clean_filename(filename, redundant_words):
"""Clean filename according to specified rules (remove numbers, repeated words)."""
filename = filename.split(':', 1)[-1]
filename = os.path.splitext(filename)[0]
words = filename.replace('_', ' ').lower().split()
if all(part.isdigit() for part in words):
return ' '.join(words)
words = [re.sub(r'\d+', ' ', word).strip() for word in words]
words = ' '.join(words).split()
unique_words = [w for w in words if w not in redundant_words]
seen = set()
cleaned_words = [
word for word in unique_words
if len(word) > 2 and not (word in seen or seen.add(word))
]
cleaned_filename = ' '.join(cleaned_words)
return cleaned_filename if cleaned_filename else "misc_files"
def find_redundant_words(files):
if not files:
return []
common_words = set(files[0].replace('_', ' ').lower().split())
for file in files[1:]:
common_words.intersection_update(file.replace('_', ' ').lower().split())
return list(common_words)
def prepare_groups(files):
if not files:
return {}
sample_filenames = [file.split(':', 1)[-1] for file in files if ':' in file]
redundant_words = find_redundant_words(sample_filenames)
groups = defaultdict(list)
for file in files:
cleaned_name = clean_filename(file, redundant_words)
groups[cleaned_name].append(file)
return groups
def show_folder_contents(event=None):
"""Display files in the selected folder."""
selection = folder_listbox.curselection()
if not selection:
return
folder_name = folder_listbox.get(selection[0])
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
# Modify folder name according to options.
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join(
[word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word
for word in folder_name.split()]
)
content_listbox.delete(0, tk.END)
folder_path_full = os.path.join(folder_path, folder_name)
if os.path.exists(folder_path_full):
if group_files:
subfolders = [f for f in os.listdir(folder_path_full) if os.path.isdir(os.path.join(folder_path_full, f))]
for subfolder in subfolders:
content_listbox.insert(tk.END, f"Subfolder: {subfolder}")
subfolder_path = os.path.join(folder_path_full, subfolder)
subfolder_files = os.listdir(subfolder_path)
for file in subfolder_files:
content_listbox.insert(tk.END, f" - {file}")
else:
files = os.listdir(folder_path_full)
for file in files:
content_listbox.insert(tk.END, file)
def load_directory():
global folder_path
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_entry.delete(0, tk.END)
parent_name_entry.insert(0, parent_folder_name)
try:
files = os.listdir(folder_path)
global groups
groups = prepare_groups(files)
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def apply_options():
update_displayed_folders()
show_folder_contents()
def update_displayed_folders():
parent_prefix = parent_name_entry.get().strip()
add_prefix = prefix_var.get()
capitalize_names = capitalize_var.get()
folder_listbox.delete(0, tk.END)
for folder_name in groups.keys():
if add_prefix:
folder_name = f"{parent_prefix} - {folder_name}"
if capitalize_names:
folder_name = ' '.join(
[word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word
for word in folder_name.split()]
)
folder_listbox.insert(tk.END, folder_name)
def execute_sorting():
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_entry.get().strip()
add_prefix = prefix_var.get()
group_files = group_files_var.get()
capitalize_names = capitalize_var.get()
file_number = int(file_number_entry.get()) if group_files else None
for folder_name, files in groups.items():
modified_folder_name = folder_name
if add_prefix:
modified_folder_name = f"{parent_prefix} - {modified_folder_name}"
if capitalize_names:
modified_folder_name = ' '.join(
[word.capitalize() if word.lower() not in {'of', 'is', 'a', 'an'} else word
for word in modified_folder_name.split()]
)
new_folder_path = os.path.join(folder_path, modified_folder_name)
os.makedirs(new_folder_path, exist_ok=True)
if group_files and file_number:
index = 0
for idx, file in enumerate(files):
subfolder_index = idx // file_number
if idx + file_number >= len(files) and subfolder_index > 0:
subfolder_index = 0
subfolder_path = os.path.join(new_folder_path, str(subfolder_index + 1))
os.makedirs(subfolder_path, exist_ok=True)
shutil.move(os.path.join(folder_path, file), os.path.join(subfolder_path, file))
else:
for file in files:
shutil.move(os.path.join(folder_path, file), os.path.join(new_folder_path, file))
messagebox.showinfo("Success", "Files sorted and organized successfully!")
update_displayed_folders()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
root = tk.Tk()
root.title("File Sorter")
frame = tk.Frame(root)
frame.pack(pady=20, padx=20)
parent_name_label = tk.Label(frame, text="Parent Folder Name:")
parent_name_label.grid(row=0, column=0, padx=10)
parent_name_entry = tk.Entry(frame, width=30)
parent_name_entry.grid(row=0, column=1, padx=10)
prefix_var = tk.IntVar()
prefix_check = tk.Checkbutton(frame, text="Add Parent Name Prefix", variable=prefix_var, command=apply_options)
prefix_check.grid(row=1, column=0, columnspan=2, pady=5)
group_files_var = tk.IntVar()
group_files_check = tk.Checkbutton(frame, text="Group by file number:", variable=group_files_var, command=apply_options)
group_files_check.grid(row=2, column=0)
file_number_entry = tk.Entry(frame, width=5)
file_number_entry.insert(0, "5") # Default for file grouping
file_number_entry.grid(row=2, column=1, sticky='w')
capitalize_var = tk.IntVar()
capitalize_check = tk.Checkbutton(frame, text="Capitalize Folder Names", variable=capitalize_var, command=apply_options)
capitalize_check.grid(row=3, column=0, columnspan=2, pady=5)
folder_listbox = tk.Listbox(frame, width=40, height=15)
folder_listbox.grid(row=4, column=0, columnspan=2, pady=5)
content_listbox = tk.Listbox(frame, width=40, height=15)
content_listbox.grid(row=4, column=2, columnspan=2, pady=5)
folder_listbox.bind("<<ListboxSelect>>", show_folder_contents)
browse_button = tk.Button(frame, text="Browse Directory", command=load_directory)
browse_button.grid(row=5, column=0, pady=10, sticky='w')
execute_button = tk.Button(frame, text="Execute", command=execute_sorting)
execute_button.grid(row=5, column=3, pady=10, sticky='e')
root.mainloop()
Key Changes
Fetching and Displaying Files:
The show_folder_contents function retrieves files from the selected folder or its subfolders (if grouped by file number) and updates the content_listbox accordingly.
Preserved Folder Name Modifications:
Uses dynamically generated folder names based on user preferences to access currently visible content.
This setup ensures all visible folders show their contents in the listbox, regardless of whether they have been subdivided into subfolders after applying grouping options. If a different directory structure applies post-execution (due to sorting into subfolders), the program queries these new directories to list their contents accurately.