Okay also replace dots in file names with _ here is the code import os
import json
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import time
import ctypes
import sys
class MassRenamer:
def init(self, root):
self.root = root
self.root.title("Mass File Renamer for Windows")
self.folder_path = tk.StringVar()
self.log_file = ".rename_log.json"
code
Assistant
# Ensure the script is running on Windows
if not sys.platform.startswith('win'):
messagebox.showerror("Unsupported OS", "This script is optimized for Windows.")
self.root.destroy()
self.create_widgets()
def create_widgets(self):
# Folder Selection
frame = tk.Frame(self.root)
frame.pack(padx=10, pady=10, fill=tk.X)
tk.Label(frame, text="Selected Folder:").pack(side=tk.LEFT)
tk.Entry(frame, textvariable=self.folder_path, state='readonly', width=50).pack(side=tk.LEFT, padx=5)
tk.Button(frame, text="Browse", command=self.browse_folder).pack(side=tk.LEFT)
# Action Buttons
action_frame = tk.Frame(self.root)
action_frame.pack(padx=10, pady=5, fill=tk.X)
tk.Button(action_frame, text="Rename Files", command=self.rename_files).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
tk.Button(action_frame, text="Revert Names", command=self.revert_names).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
# Log Display
tk.Label(self.root, text="Status Log:").pack(anchor='w', padx=10)
self.log_text = scrolledtext.ScrolledText(self.root, height=15, state='disabled')
self.log_text.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
def browse_folder(self):
folder_selected = filedialog.askdirectory()
if folder_selected:
self.folder_path.set(folder_selected)
self.log(f"Selected folder: {folder_selected}")
def log(self, message):
self.log_text.config(state='normal')
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
self.log_text.insert(tk.END, f"{timestamp} - {message}\n")
self.log_text.see(tk.END)
self.log_text.config(state='disabled')
def set_hidden_attribute(self, filepath):
"""
Sets the Hidden attribute on the specified file.
"""
FILE_ATTRIBUTE_HIDDEN = 0x02
try:
ctypes.windll.kernel32.SetFileAttributesW(str(filepath), FILE_ATTRIBUTE_HIDDEN)
self.log(f"Set Hidden attribute for '{os.path.basename(filepath)}'")
except Exception as e:
self.log(f"Failed to set Hidden attribute for '{os.path.basename(filepath)}': {e}")
def rename_files(self):
folder = self.folder_path.get()
if not folder:
messagebox.showwarning("No Folder Selected", "Please select a folder first.")
return
mapping = {}
try:
for filename in os.listdir(folder):
original_path = os.path.join(folder, filename)
if os.path.isfile(original_path):
new_filename = filename.replace(" ", "_")
if new_filename != filename:
new_path = os.path.join(folder, new_filename)
if os.path.exists(new_path):
self.log(f"Skipped '{filename}' -> '{new_filename}': Target exists.")
continue
# Get original modification time
mod_time = os.path.getmtime(original_path)
# Rename the file
os.rename(original_path, new_path)
# Restore modification time
os.utime(new_path, (mod_time, mod_time))
# Record the renaming and modification time
mapping[new_filename] = {
"original_name": filename,
"original_mod_time": mod_time
}
self.log(f"Renamed '{filename}' -> '{new_filename}'")
if mapping:
log_path = os.path.join(folder, self.log_file)
# Save mapping to log file
with open(log_path, 'w', encoding='utf-8') as f:
json.dump(mapping, f, indent=4)
self.log(f"Renaming completed. Log saved to '{self.log_file}'.")
# Set the log file as hidden
self.set_hidden_attribute(log_path)
messagebox.showinfo("Success", "Files have been renamed successfully.")
else:
self.log("No files needed renaming.")
messagebox.showinfo("No Changes", "No files were renamed.")
except Exception as e:
self.log(f"Error during renaming: {e}")
messagebox.showerror("Error", f"An error occurred: {e}")
def revert_names(self):
folder = self.folder_path.get()
if not folder:
messagebox.showwarning("No Folder Selected", "Please select a folder first.")
return
log_path = os.path.join(folder, self.log_file)
if not os.path.exists(log_path):
self.log("No rename log found. Cannot revert.")
messagebox.showwarning("No Log Found", "No rename log found to revert.")
return
try:
with open(log_path, 'r', encoding='utf-8') as f:
mapping = json.load(f)
for new_name, data in mapping.items():
original_name = data["original_name"]
original_mod_time = data.get("original_mod_time")
new_path = os.path.join(folder, new_name)
original_path = os.path.join(folder, original_name)
if os.path.exists(new_path):
if os.path.exists(original_path):
self.log(f"Skipped reverting '{new_name}' to '{original_name}': Original file exists.")
continue
# Rename back to original
os.rename(new_path, original_path)
self.log(f"Reverted '{new_name}' -> '{original_name}'")
# Restore original modification time if available
if original_mod_time:
os.utime(original_path, (original_mod_time, original_mod_time))
else:
self.log(f"File '{new_name}' does not exist. Skipped.")
# Remove the log file after reverting
os.remove(log_path)
self.log(f"Reversion completed. Log file '{self.log_file}' removed.")
messagebox.showinfo("Success", "Files have been reverted successfully.")
except Exception as e:
self.log(f"Error during reversion: {e}")
messagebox.showerror("Error", f"An error occurred: {e}")
if name == "main":
root = tk.Tk()
app = MassRenamer(root)
root.mainloop()
Certainly! I understand you want to modify your MassRenamer application to replace dots (.) in file names with underscores (_). This can be particularly useful if you want to avoid issues related to multiple dots in file names or for consistency in naming conventions.
Below is the updated code with the necessary changes to replace dots in file names with underscores. Additionally, I'll ensure that dots in file extensions (e.g., .txt, .jpg) remain intact to preserve the file type information.
Updated Code
python
import os
import json
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import time
import ctypes
import sys
class MassRenamer:
def __init__(self, root):
self.root = root
self.root.title("Mass File Renamer for Windows")
self.folder_path = tk.StringVar()
self.log_file = ".rename_log.json"
# Ensure the script is running on Windows
if not sys.platform.startswith('win'):
messagebox.showerror("Unsupported OS", "This script is optimized for Windows.")
self.root.destroy()
self.create_widgets()
def create_widgets(self):
# Folder Selection
frame = tk.Frame(self.root)
frame.pack(padx=10, pady=10, fill=tk.X)
tk.Label(frame, text="Selected Folder:").pack(side=tk.LEFT)
tk.Entry(frame, textvariable=self.folder_path, state='readonly', width=50).pack(side=tk.LEFT, padx=5)
tk.Button(frame, text="Browse", command=self.browse_folder).pack(side=tk.LEFT)
# Action Buttons
action_frame = tk.Frame(self.root)
action_frame.pack(padx=10, pady=5, fill=tk.X)
tk.Button(action_frame, text="Rename Files", command=self.rename_files).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
tk.Button(action_frame, text="Revert Names", command=self.revert_names).pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
# Log Display
tk.Label(self.root, text="Status Log:").pack(anchor='w', padx=10)
self.log_text = scrolledtext.ScrolledText(self.root, height=15, state='disabled')
self.log_text.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
def browse_folder(self):
folder_selected = filedialog.askdirectory()
if folder_selected:
self.folder_path.set(folder_selected)
self.log(f"Selected folder: {folder_selected}")
def log(self, message):
self.log_text.config(state='normal')
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
self.log_text.insert(tk.END, f"{timestamp} - {message}\n")
self.log_text.see(tk.END)
self.log_text.config(state='disabled')
def set_hidden_attribute(self, filepath):
"""
Sets the Hidden attribute on the specified file.
"""
FILE_ATTRIBUTE_HIDDEN = 0x02
try:
ctypes.windll.kernel32.SetFileAttributesW(str(filepath), FILE_ATTRIBUTE_HIDDEN)
self.log(f"Set Hidden attribute for '{os.path.basename(filepath)}'")
except Exception as e:
self.log(f"Failed to set Hidden attribute for '{os.path.basename(filepath)}': {e}")
def rename_files(self):
folder = self.folder_path.get()
if not folder:
messagebox.showwarning("No Folder Selected", "Please select a folder first.")
return
mapping = {}
try:
for filename in os.listdir(folder):
original_path = os.path.join(folder, filename)
if os.path.isfile(original_path):
# Split the filename into name and extension
name, ext = os.path.splitext(filename)
# Replace spaces and dots in the name part
new_name = name.replace(" ", "_").replace(".", "_")
# Combine the new name with the original extension
new_filename = new_name + ext
if new_filename != filename:
new_path = os.path.join(folder, new_filename)
if os.path.exists(new_path):
self.log(f"Skipped '{filename}' -> '{new_filename}': Target exists.")
continue
# Get original modification time
mod_time = os.path.getmtime(original_path)
# Rename the file
os.rename(original_path, new_path)
# Restore modification time
os.utime(new_path, (mod_time, mod_time))
# Record the renaming and modification time
mapping[new_filename] = {
"original_name": filename,
"original_mod_time": mod_time
}
self.log(f"Renamed '{filename}' -> '{new_filename}'")
if mapping:
log_path = os.path.join(folder, self.log_file)
# Save mapping to log file
with open(log_path, 'w', encoding='utf-8') as f:
json.dump(mapping, f, indent=4)
self.log(f"Renaming completed. Log saved to '{self.log_file}'.")
# Set the log file as hidden
self.set_hidden_attribute(log_path)
messagebox.showinfo("Success", "Files have been renamed successfully.")
else:
self.log("No files needed renaming.")
messagebox.showinfo("No Changes", "No files were renamed.")
except Exception as e:
self.log(f"Error during renaming: {e}")
messagebox.showerror("Error", f"An error occurred: {e}")
def revert_names(self):
folder = self.folder_path.get()
if not folder:
messagebox.showwarning("No Folder Selected", "Please select a folder first.")
return
log_path = os.path.join(folder, self.log_file)
if not os.path.exists(log_path):
self.log("No rename log found. Cannot revert.")
messagebox.showwarning("No Log Found", "No rename log found to revert.")
return
try:
with open(log_path, 'r', encoding='utf-8') as f:
mapping = json.load(f)
for new_name, data in mapping.items():
original_name = data["original_name"]
original_mod_time = data.get("original_mod_time")
new_path = os.path.join(folder, new_name)
original_path = os.path.join(folder, original_name)
if os.path.exists(new_path):
if os.path.exists(original_path):
self.log(f"Skipped reverting '{new_name}' to '{original_name}': Original file exists.")
continue
# Rename back to original
os.rename(new_path, original_path)
self.log(f"Reverted '{new_name}' -> '{original_name}'")
# Restore original modification time if available
if original_mod_time:
os.utime(original_path, (original_mod_time, original_mod_time))
else:
self.log(f"File '{new_name}' does not exist. Skipped.")
# Remove the log file after reverting
os.remove(log_path)
self.log(f"Reversion completed. Log file '{self.log_file}' removed.")
messagebox.showinfo("Success", "Files have been reverted successfully.")
except Exception as e:
self.log(f"Error during reversion: {e}")
messagebox.showerror("Error", f"An error occurred: {e}")
if __name__ == "__main__":
root = tk.Tk()
app = MassRenamer(root)
root.mainloop()
Key Changes Explained
Preserving File Extensions:
To ensure that file extensions remain unchanged (e.g., .txt, .jpg), we split the filename into two parts: the name and the extension using os.path.splitext.
Code Snippet:
python
name, ext = os.path.splitext(filename)
Replacing Dots and Spaces in the Filename (Excluding Extension):
After splitting, we replace both spaces (" ") and dots (".") in the name part with underscores ("_").
Combine the modified new_name with the original ext to form the new_filename.
Code Snippet:
python
new_filename = new_name + ext
Handling Hidden Files and Preservation:
The script sets the .rename_log.json file as hidden after renaming using the set_hidden_attribute method.
This ensures that the log file used for reverting names remains hidden from regular view.
Logging and Error Handling:
Comprehensive logging has been maintained to record every action, whether it's a successful rename, skipped file due to existing target, or any errors encountered.
This helps in troubleshooting and provides transparency during the renaming process.
Example
Before Renaming:
code
example file.v1.txt
another.example file.docx
sample.file.name.pdf
Before performing mass renaming operations, especially when dealing with critical files, ensure you have backups. This precaution helps prevent accidental data loss.
Testing:
Test the script on a small set of sample files to ensure it behaves as expected before applying it to larger directories.
Extensibility:
You can further enhance the script to allow customization of replacement characters or patterns, providing more flexibility based on user needs.
User Feedback:
Consider adding a preview feature that shows a list of proposed changes before actually performing the renaming. This can help users verify changes beforehand.
Feel free to integrate these changes into your application and let me know if you need further assistance or additional features!